Adding a user to many security groups in Active Directory using PowerShell is simple. You can use the Add-ADPrincipalGroupMembership
cmdlet. This cmdlet allows you to add a user to one or more security groups.
Here’s an example of how you might use this cmdlet (this is an OK solution):
# Define the user you want to add to the security groups
$user = Get-ADUser -Identity "Jeffrey"
# Define the security groups you want to add the user to
$groups = @("DelegatedDomainJoiner", "App1_RO", "App2_Admin")
# We now use a foreach loop to add the user to each group
foreach ($group in $groups)
{
Add-ADPrincipalGroupMembership -Identity $user -MemberOf $group
}
The Add-ADPrincipalGroupMembership
cmdlet, is used inside a foreach
loop. The user stored in the $user
variable to each security group stored in the $groups
array. But this method requires you to loop through all the groups and add the user to each one. This is OK, but we can do it a bit better from code readability standpoint.
We can use the -Members
parameter of the Add-ADGroupMember
cmdlet instead. To add the user to many security groups at once, take a look at the example below (this is a BETTER solution):
# Define the user you want to add to the security groups
$user = Get-ADUser -Identity "Jeffrey"
# Define the security groups you want to add the user to
$groups = @("DelegatedDomainJoiner", "App1_RO", "App2_Admin")
# This command will add the user to all the groups at once
Add-ADGroupMember -Identity $groups -Members $user
Here, we are using the Add-ADGroupMember
cmdlet. The user stored in the $user
variable to all the security in a single command. I find this method to be much more concise.
Note: Of course, you will need the correct permissions in Active Directory and the Active Directory PowerShell module.