Brad
Brad

Reputation: 2195

Script is outputting an extra 0

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

Upvotes: 1

Views: 396

Answers (2)

Shay Levy
Shay Levy

Reputation: 126772

You need to capture (or ignore) the output of the PropertiesToLoad.Add method, otherwise you'll get a value for each property in $colPropList.

foreach ($i in $colPropList){[void]$objSearcher.PropertiesToLoad.Add($i)}

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.

$strCategory = "computer"
$colProplist = "name","distinguishedname"

$searcher = [adsisearcher]"(objectCategory=$strCategory)"
$searcher.PropertiesToLoad.AddRange($colProplist)
$searcher.FindAll() | Foreach-Object {$_.Properties}

Upvotes: 5

Seth Flowers
Seth Flowers

Reputation: 9190

I suspect your foreach loop is outputting the result when calling PropertiesToLoad.Add.

Try piping to out-null, like so:

foreach ($i in $colPropList){
    $objSearcher.PropertiesToLoad.Add($i) | out-null
}

Upvotes: 1

Related Questions