i would like to know how to add azure ad users to azure ad groups. To do this, I would like the script to validate if the group exists. If so, check if the user is already a member of the group. If not, add the user to the group. The problem I have is that I can't figure out what I'm doing wrong in the catch/else part. It appears 2x when the group does not exist. Can you help me?
Connect-AzureAD
### Azure AD Users ###
$Users =
@"
UPN
adminuser.test@contoso.com
user.test@contoso.com
"@ | ConvertFrom-Csv -Delimiter ','
### Azure AD GROUP ###
$Groups =
@"
Group
test-lab
test-dev
test-prod
"@ | ConvertFrom-Csv -Delimiter ','
foreach($user in $Users) {
$AzureADUser = Get-AzureADUser -Filter "UserPrincipalName eq '$($user.UPN.Trim())'"
if($AzureADUser -ne $null) {
try {
Foreach($group in $Groups){
$AzureADGroup = Get-AzureADGroup -Filter "DisplayName eq '$($Group.Group.Trim())'"
$isUserMemberOfGroup = Get-AzureADGroupMember -ObjectId $AzureADGroup.ObjectId -All $true | Where-Object {$_.UserPrincipalName -like "*$($AzureADUser.UserPrincipalName)*"}
if($isUserMemberOfGroup -ne $null) {
write-host "$($user.upn) is already a member of Azure AD Group: $($Group.group.trim())." -ForegroundColor Green
}
if($isUserMemberOfGroup -eq $null) {
Add-AzureADGroupMember -ObjectId $AzureADGroup.ObjectId -RefObjectId $AzureADUser.ObjectId
write-host "$($user.upn) added to Azure AD group: $($Group.group.trim())." -ForegroundColor Green
}
}
}
catch { ### warning error if group doesn't exist ###
Write-Warning " Azure AD Group $($Group.Group.Trim()) doesn't exist."
}
}
else { ### Write Warning error if user doesn't exist###
$message = " $($user.upn) doesn't exist"
Write-Warning "$message"
}
}