Search code examples
powershellactive-directoryactive-directory-group

How can I clone a GroupOfNames Active Directory Object?


I'm writing a script to take one GroupOfNames object and create a second group with the first groups members. It seems like it would be a very simple piece of code:

$obj = Get-ADObject -Server "$server" -SearchBase $SearchBase -Filter "name -eq '$GroupName'" -Properties Member
New-ADObject -Server "$server" -Path $SearchBase -Type 'GroupOfNames' -name "$NewGroupName" -OtherAttributes @{'Member'= ($($obj.Member))}

When I run this the $obj gets created and I can display both the GroupOfNames information, as well as the list of members. But when it calls the New-ADObject cmdlet, I get the following error:

New-ADObject : Unable to contact the server. This may be because this server does not exist, it is currently down, or it does not have the Active Directory Web Services running.

I've tried multiple variations of the code and all fail with similar errors.

Interestingly, if I loop through the list of members and add them to the group one at a time, it works, but it just takes way too long (an hour+ vs seconds).


Solution

  • After some trial and error, I found that I could reliably add about 6000 members at a time. Here's the basic flow:

    (Get-ADObject -Server "$server" -SearchBase $SearchBase -Filter { name -eq "$GroupName" } -Properties Member).Member | %{
        $SubList += [string] $_
        if($SubList.count -ge 6000) {
            Set-ADObject -Server "$server" -Identity $NewGroup -Add @{'Member'= ($SubList)}
            $SubList = @()
        }
    }
    if($SubList.count -gt 0) {
        Set-ADObject -Server "$server" -Identity $NewGroup -Add @{'Member'= ($SubList)}
    }
    

    Thank you @Raf for the push in the right direction.