Tuesday, June 28, 2016

Adding Multiple Computer Objects to AD Group

Hi folks,

Just wanted to share with you about an adventure that I had when trying to add multiple computer objects for my server into an AD group. Let us imagine that we have set up naming convention where names for computer objects are well organized.

Add-ADGroupMember is the one to be used when you're adding your server objects into AD group and you can read about it here.  A command to add a single server object to a group is quite straightfoward:

Add-ADGroupMember -Identity SvcAccPSOGroup -Members SQL01

And it seems to be straightforward when you're trying to add more than 1 server, like below:

Add-ADGroupMember -Identity SvcAccPSOGroup -Members SQL01,SQL02

However, when I tried it I got an error. Therefore I decided to run my server objects one-by-one. To avoid typing command for each server objects I queried AD for all of them and fed to the $Mem variable. Please note that I'm using well defined naming convention and therefore it's simple for me to do so. After this I'm running the Add-ADGroupMember command against every server in the $Mem variable. The final code is as below:


 $Mem = Get-ADComputer -Filter {Name -like "MYSERVER00*"}
 $Mem |foreach {Add-ADGroupMember -Identity "MY Group Name" -Members $_.DistinguishedName}

And finally you can confirm group membership by executing the following command:

 Get-ADGroupMember -Identity "MY Group Name"

Now let's consider yet another scenario. Imagine you have mailbox (or CAS) servers in your Exchange platform that share part of common name while the other part varies depending on the AD site. Below code can be run from Exchange management shell with the AD PowerShell module loaded. First we retrieve Exchange servers of a certain role (Mailbox in my example) and feed them into a variable just as above, and this is where Exchange Management shell is in play. The we will add them to the group where they should be added.

The code will be as below:

$MbxMem = Get-MailboxServer EXCH* |foreach {Get-ADComputer -Identity $
_.Name}
 $MbxMem |foreach {Add-ADGroupMember -Identity "MY Group Name" -Members $_.DistinguishedName}


I hope you'll find it helpful.

Enjoy!