Powershell: Using PoSH to Search Across Multiple Domains in Forest

I was recent­ly asked to get a quick report of all Win­dows 7 com­put­ers with­in a mul­ti-domain AD for­est.  After bang­ing my head into the key­board for a while, I final­ly fig­ured it out.  The script below should do the trick.

Also, if you use the Oper­at­ingSys­temVer­sion attribute, you will find that Serv­er 2008 R2 shares ver­sion “6.1 (7600)”.  So, the best way to find Win­dows 7 only, is to search for “Win­dows 7*” with the wild­card char­ac­ter against the Oper­at­ingSys­tem attribute.  That will ensure all Win­dows 7 ver­sions are returned and will exclude Serv­er 2008 R2 from your results.

#Get Domain List
$objForest = [System.DirectoryServices.ActiveDirectory.Forest]::GetCurrentForest()
$DomainList = @($objForest.Domains | Select-Object Name)
$Domains = $DomainList | foreach {$_.Name}

#Act on each domain
foreach($Domain in ($Domains))
	Write-Host "Checking $Domain" -fore red
	$ADsPath = [ADSI]"LDAP://$Domain"
	$objSearcher = New-Object System.DirectoryServices.DirectorySearcher($ADsPath)
	$objSearcher.Filter = "(&(objectCategory=Computer)(operatingSystem=Windows 7*))"
	$objSearcher.SearchScope = "Subtree"

	$colResults = $objSearcher.FindAll()
	foreach ($objResult in $colResults)
		$Computer = $objResult.GetDirectoryEntry()


  1. Neat use case of System.DirectoryServices.ActiveDirectory.Forest.

    Queries as such are a must every time you have to query a mul­ti-domain for­est. By manip­u­lat­ing the LDAP query under fil­ter, you can pret­ty much search for any­thing.


Comments are closed.