Azure AD & PowerShell How To: Add multiple users or a group into multiple groups?

Copper Contributor

Hello Forum

 

I have a bunch of users (Many users), and I want to add all them into many multiple Azure AD security groups (Nothing On-Prem), Something like:

 

Users:

User1,User2,User3...etc. => Of course, I can add all these users into one security group e.g. called "All" group.

 

Groups:

All users (Or, All Group) are added into: Group1

All users (Or, All Group) are added into: Group2

All users (Or, All Group) are added into: Group3

...etc.

 

It is so hard to perform this operation manually, and I tried with PowerShell below but it keeps failing.

 

$Allusers = Import-Csv "C:\test\users.csv"
$secgrp = Import-Csv "C:\test\groups.csv"
$Sgroup = @()
$secgrp | ForEach-Object { $Sgroup += $_.group }
foreach ($grp in $sgroup) {
$GP = Get-ADGroup $grp
foreach ($user in $Allusers) { Try
{ $Aduser = Get-ADUser -Identity $user.Accounts -ErrorAction SilentlyContinue
if ($Aduser -ne $null) {
Add-ADGroupMember $GP -Members $Aduser.SamAccountName -Confirm:$false
}
}
catch { $Error[0].ToString() | Out-File "C:\test\userlog.txt" -Append -Force }

}
}

 

Could you please help me out adding all these users or the group that contains them all into all these Azure AD security groups?

 

0 Replies