Greg`s Tech blog

Sorting Computers by OS with PowerShell

Wednesday 11 of May, 2011
We needed to move a hundred or so computers into different OUs based on their operating system today. We weren't sure how to approach this at first, but a quick search revealed that AD tracks a computer account's Operating System in an attribute called, oddly enough, operatingSystem. With that in mind, we developed the following Powershell commandline to find and move Windows XP acounts.

Sorting Computers with Powershell
get-adcomputer -SearchScope onelevel -searchbase "ou=laptops,ou=technical,ou=workstations,ou=city,dc=ourco,dc=com" -filter 'operatingsystem -like "Windows XP*" ' | move-adobject -targetpath "ou=FDCC,ou=laptops,ou=technical,ou=workstations,ou=city,dc=ourco,dc=com" -passthru

To talk this through a bit, the first part of this is the query to locate computer accounts:
get-adcomputer -SearchScope onelevel 
  -searchbase "ou=laptops,ou=technical,ou=workstations,ou=city,dc=ourco,dc=com" 
   -filter 'operatingsystem -like "Windows XP*" '

This command uses the get-computer cmdlet to
  • search an OU specified by the -Searchbase parameter.
  • The -SearchScope parameter restricts this search to only this OU (not sub OUs)
  • The -Filter "operatingSystem -like "Windows XP*" find computers starting with Windows XP and ends with anything
  • Sends the results down the pipeline

The second half of this command
move-adobject -targetpath "ou=FDCC,ou=laptops,ou=technical,ou=workstations,ou=city,dc=ourco,dc=com" -passthru

uses the Move-ADObject cmdlet to move the AD objects passed through the pipeline to the AD container specified by -Targetpath.

It took us a total of 10 minutes to work through the help command to define the search and move action, test using the -whatif switch and implement. We then repeated the whole thing to search for Windows 7 PCs and move them into a separate container.