Frage

I wrote a script to find GID's in AD, this is working fine, the issue I'm having is filtering out the blank (null lines)

 $searcher=[adsisearcher]"(objectCategory=user)"
$result = $searcher.FindAll()
$result | Select-Object @{Name="DN";Expression+{$_.properties.distinguishedname}},@{Name="gid";Expression={$_.properties.gidnumber }} |Sort-Object -Property gid 
War es hilfreich?

Lösung

I find it odd that you would be getting blank lines with that code. Can't think of a scenario where the distinguishedname of a user is null. The one issue with your code that I do see might just be a typo in your first calculated expression:

@{Name="DN";Expression+{$_.properties.distinguishedname}}

should instead be

@{Name="DN";Expression={$_.properties.distinguishedname}}

However that should have just made a syntax error that would be easily caught before execution.

Filtering Blanks

A real easy PowerShell way to deal with this is to use a simple Where-Object clause. For argument sake lets say that the GID could be empty/null.

$result | Select-Object @{Name="DN";Expression={$_.properties.distinguishedname}},@{Name="gid";Expression={$_.properties.gidnumber }} | Where-Object{$_.GID} | Sort-Object -Property gid

A null or empty value evaluates to False in PowerShell. Where-Object{$_.GID} will only allow objects with a populated property for GID to pass as output. You will get similar results from string static methods as well. These would also add readability to your code.

... | Where-Object{[string]::IsNullOrWhiteSpace($_.GID)} | ...

There is also [string]::IsNullOrEmpty()

Andere Tipps

Sort Object has a -unique property which will remove most of the blank lines, all but one as you have guessed. You could also pipe to a

where-object -ne '`n'

or something similar, let me know if I should elaborate that.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top