I have the following powershell script which binds to an active directory OU and lists the computers. It seems to work fine except that it ouputs an extra 0 – I’m not sure why. Can anyone help?
$strCategory = "computer"
$objDomain = New-Object System.DirectoryServices.DirectoryEntry("LDAP:// OU=Computers,OU=datacenter,DC=ourdomain,DC=local")
$objSearcher = New-Object System.DirectoryServices.DirectorySearcher($objDomain)
$objSearcher.Filter = ("(objectCategory=$strCategory)")
$colProplist = "name"
foreach ($i in $colPropList){$objSearcher.PropertiesToLoad.Add($i)}
$colResults = $objSearcher.FindAll()
foreach ($objResult in $colResults)
{
$objComputer = $objResult.Properties;
$objComputer.name
}
Output:
0
Server1
Server2
Server3
You need to capture (or ignore) the output of the PropertiesToLoad.Add method, otherwise you’ll get a value for each property in $colPropList.
You can simplify and shorten your script and load a bunch of properties in one call without using a foreach loop. Another benefit of the AddRange method is that it doesn’t output the length of requested properties, so there’s no need to capture anything.