0

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 
JoeRod
  • 899
  • 8
  • 20
  • 30
  • 1
    Try adding a `Where` statement like `| Where {$_.someproperty -ne $null}` – Brock Hensley Sep 18 '13 at 19:06
  • What do you mean by "blank line"? You select several properties from the objects your search returned. Do you want to omit objects where all properties are `$null`? Objects where at least one of them is `$null`? Objects where one particular property is `$null`? – Ansgar Wiechers Sep 18 '13 at 19:22
  • Similar to Brocks comment, add a `| ? {$_}` to the end of the line. – xXhRQ8sD2L7Z Oct 20 '15 at 03:21

2 Answers2

3

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()

Community
  • 1
  • 1
Matt
  • 45,022
  • 8
  • 78
  • 119
-1

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.

MDMoore313
  • 3,233
  • 1
  • 23
  • 38