Adding a group of computers to an AD Group using PowerShell

PowerShell is a lot of fun but I don’t always get to play with it.  Anytime I have to do large tasks that move a lot of simple data or AD type tasks then I’ll sometimes pull it out.

Recently we installed Windows 7 across our district.  During that process we renamed all the computers because our old naming convention wasn’t always followed and it created a lot of confusion and inconsistency.

All our library staff computers have a special application that allows them to download barcodes that are read using a handheld barcode scanner for inventories.  This previously was pushed out by a group policy.  Since the computers were erased during the Win7 install and the computer names had changed we had about 25 computers that needed to be added to the group again.

Sounds like a perfect chore for PowerShell.

First of all, I forgot the name of the group that they needed to be added to, but I knew it had “dolphin” in the name, since that is the name of the software.  Active Directory Users and Computers (ADUC) won’t let you search on a portion of the name, just the beginning or the end.  Not much help there.

PowerShell makes this trivial:

Get-ADGroup -filter {name -like "*dolph*"}

This returned the following:

DistinguishedName : CN=g-InstallLibraryDolphin,OU=Computer,OU=Software Install,DC=valverde,DC=edu
GroupCategory     : Security
GroupScope        : Global
Name              : g-InstallLibraryDolphin
ObjectClass       : group
ObjectGUID        : 0909537b-ddcc-41c1-bd37-667fdb943a95
SamAccountName    : g-InstallLibraryDolphin
SID               : S-1-5-21-1659004503-746137067-682003330-69446

That’s the one!

Our naming convention for or library computers is wXX-Library, where XX is the two character code for the school the computer is at.  However, simply filtering on this wouldn’t help, because we name all our library student computers as follows: wXX-LibrarySYY, where YY is simply a number stating at 01 and goes up for however many student computers are in the library.

So, here is the PowerShell command that stores all our library staff computers into a $libcomps variable, excluding the student machines:

$libcomps = Get-ADComputer -filter {name -like "*library*" -and name -notlike "*libraryS*"}

Since you cannot pipe computer objects straight into the Add-ADGroupMember commandlet (why, I have no idea but it doesn’t make sense to me) you have to iterate over the $libcomps collection and add them one by one:

foreach ($c in $libcomps) {Add-ADGroupMember g-InstallLibraryDolphin -Members $c}

The command ran for about .25 seconds and did all the work for me.  I think researching the right commands to use took about 2 minutes, which is still faster than had I had to move them all over one by one. 

Heck, this post took longer than the entire task all together. Smile