Thursday, April 8, 2010

Powershell script to find a specific OS in a domain

Here's a piece of code modified from this scripting guy post that allows you to list computer accounts with specific operating systems that aren't disabled in your domain. It's written as a function so you just have to write your query string and pass it to the function. aka GetDomainComps *2008* will return all the AD computer accounts with 2008 in their name.

Function GetDomainComps
{param ($strOS)

$strCategory = "computer"

$objDomain = New-Object System.DirectoryServices.DirectoryEntry

$objSearcher = New-Object System.DirectoryServices.DirectorySearcher
$objSearcher.SearchRoot = $objDomain
$objSearcher.Filter = "(&(objectCategory=$strCategory)(operatingSystem=$strOS)(!(userAccountControl:1.2.840.113556.1.4.803:=2)))"

$colProplist = "name"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}

$colResults = $objSearcher.FindAll()

foreach ($objResult in $colResults)
{$objComputer = $objResult.Properties; $}

GetDomainComps *2003*