Reputation: 13
I am trying to write a script that will update group memberships in AD based on members of an OU. The little script is working fine when I specify the group name and OU name and then do the comparison:
$Group = "GroupA"
$OU = "OU=ContainerA,DC=DC1,DC=ccompany,DC=com"
$users = $(get-aduser -filter "*" -SearchBase $OU)
$groupmembers = Get-ADGroupMember -Identity $Group
switch (Compare-Object -ReferenceObject $groupmembers -DifferenceObject $users -property samaccountname){
{$_.SideIndicator -eq "=>"} {add-adgroupmember -identity $group -member $_.samaccountname}
{$_.SideIndicator -eq "<="} {remove-adgroupmember -identity $group -member $_.samaccountname -confirm:$false} }
}
Of course this is fine for a single Group and OU, however, I need to do this for about 10 groups and OUs so rather than copy pasting the entire thing 10 times, I figured the smart way will be to create a function and then call it 10 times. I changed the code into a function:
Function Build ([String]$Group, [String]$OU){
$users = $(get-aduser -filter "*" -SearchBase $OU)
$groupmembers = Get-ADGroupMember -Identity $Group
switch (Compare-Object -ReferenceObject $groupmembers -DifferenceObject $users -property samaccountname){
{$_.SideIndicator -eq "=>"} {add-adgroupmember -identity $group -member $_.samaccountname}
{$_.SideIndicator -eq "<="} {remove-adgroupmember -identity $group -member $_.samaccountname -confirm:$false} }
}
Build ("GroupA", "OU=ContainerA,DC=DC1,DC=ccompany,DC=com")
Build ('GroupB", "OU=ContainerB,DC=DC1,DC=ccompany,DC=com")
However, when I run the above script I keep getting following Error:
Get-ADUser : An empty SearchBase is only supported while connected to a GlobalCatalog.
Can you please please point out what I am doing wrong in trying to convert the first code into a function?
Thanks
Upvotes: 1
Views: 842
Reputation: 72660
Your trouble is in the way you are calling the function Build
just try :
Build "GroupA" "OU=ContainerA,DC=DC1,DC=ccompany,DC=com"
Build 'GroupB" "OU=ContainerB,DC=DC1,DC=ccompany,DC=com"
or
Build -Group "GroupA" -ou "OU=ContainerA,DC=DC1,DC=ccompany,DC=com"
When you call a function you do not need ()
neither ,
. Be careful ,
is the array separator
Upvotes: 1