Powershell – Adding multiple users from a group to an Active Directory group using Powershell

active-directorypowershell

I have a powershell script that is supposed to go through a specific ou and store the groups into a variable $groups. Here is the code I use in the script:

$Groups = Get-ADGroup -Properties * -Filter * -SearchBase "OU=GFS-USERS,OU=AFS-OU-Groups,OU=AFS,OU=FA,OU=DEPARTMENTS,DC=ou,DC=ad3,DC=blabla,DC=com" -Server "ou.ad3.blabla.com"
Foreach($G In $Groups)
{
    Write-Host $G.Name
    Write-Host "-------------"
    $G.Members
}

This step seems to work fine.

In my next part of my script I have it go through each group and attempt to add the users from each group into a group where they should all be combined. The code is as follows:

foreach ($group in $groups)
{
    Add-ADGroupMember -Identity "CN=test,OU=AFS-OU-ACLs-EDMS,OU=AFS-OU-Groups,OU=AFS,OU=FA,OU=DEPARTMENTS,DC=ou,DC=ad3,DC=blabla,DC=com" -Members (Get-ADGroupMember $group) -Server "ou.ad3.blabla.com"
}       

When I run the script, it works fine for all users from:

OU=AFS,OU=FA,OU=DEPARTMENTS,DC=ou,DC=ad3,DC=blabla,DC=com

but for all other users I get the following error:

Add-ADGroupMember : The server is unwilling to process the request
At line:1 char:22

Does anyone know if this is a permissions issue or if there is something I am doing wrong?

Best Answer

Consider looping through and adding members to the new group one at a time from the old group.

$CombinedGroup = ...
$Groups = Get-ADGroup ...
foreach ($Group in $Groups) {
    $Members = GetADGroupMember $Group
    foreach ($Member in $Members) {
        Get-ADUser $Member | Set-ADGroup -Identity $CombinedGroup -Add $Member
        }
    }
}