Add multiple users to multiple groups in AD using PowerShell

Problem:
I needed to add multiple users all in the same OU to multiple different groups using PowerShell

Solution:
Run the below PowerShell commands (substituting the OU and Group names for your own ones)

Get-ADUser -SearchBase OU=Users,OU=Robnet,DC=robnet,DC=local -Filter * | % {Add-ADGroupMember -Identity Script Test Group -Members $_ } 

Get-ADUser -SearchBase OU=Users,OU=Robnet,DC=robnet,DC=local -Filter * | % {Add-ADGroupMember -Identity Script Test Group2 -Members $_ } 

Get-ADUser -SearchBase OU=Users,OU=Robnet,DC=robnet,DC=local -Filter * | % {Add-ADGroupMember -Identity Script Test Group3 -Members $_ } 

 

The best way to get the syntax for you OU is to copy it from adsiedit as below:

Add multiple users to multiple groups in AD

Thanks to one of my readers, Ryan Chau for improving on my code for this process:

# Put user out side like this
 $Users = @("Ryan Chau","Robin Clarke")

# OR you can put it in a txt file, your choice
 # $Users = Get-Content "B:\users.txt"

$Groups = Get-Content "B:\Groups.txt"
foreach ($User in $Users){
 foreach ($Group in $Groups)
 {
 $Sam = (Get-ADUser -Filter {Name -like $User}).SamAccountName
 write-host "Added $User ID: $Sam to $Group"
Add-ADGroupMember -Identity $Group -Members $Sam
 }
 }

4 Replies to “Add multiple users to multiple groups in AD using PowerShell”

  1. Robin –
    Great blog. This is Ryan from Toronto. I just want to add my 2 cent and hope that help few IT mates out there. Nothing wrong with your command, you just add 1 user to multiple groups with that command btw. But I’ve using scripting for this kind of request for a while. “Multiple Users to Multiple Groups.”

    # Put user out side like this
    $Users = @(“Ryan Chau”,”Robin Clarke”)

    # OR you can put it in a txt file, your choice
    # $Users = Get-Content “B:\users.txt”

    $Groups = Get-Content “B:\Groups.txt”
    foreach ($User in $Users){
    foreach ($Group in $Groups)
    {
    $Sam = (Get-ADUser -Filter {Name -like $User}).SamAccountName
    write-host “Added $User ID: $Sam to $Group”
    Add-ADGroupMember -Identity $Group -Members $Sam
    }
    }

    Have a good day,
    Ryan Chau

  2. I modified Ryan’s script a bit to select users based on OU:
    #–Define variables–
    #Set OU
    $userou = “OU=Training,OU=Company,OU=Employees,DC=contonso,DC=local”
    #Read users from OU
    $Users = Get-ADUser -SearchBase $userou -Filter *
    #Set source file with groups, 1 group per line
    $GroupsSourcefile = “\\server.contoso.local\share$\Groups.txt”

    #Add users to groups
    $Groups = Get-Content $GroupsSourcefile
    foreach ($User in $Users){
    foreach ($Group in $Groups)
    {
    write-host “Added $User ID: $Sam to $Group”
    Add-ADGroupMember -Identity $Group -Members $User
    }
    }

Leave a Reply

Your email address will not be published. Required fields are marked *