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 
3
  • 1
    Try adding a Where statement like | Where {$_.someproperty -ne $null} Commented Sep 18, 2013 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? Commented Sep 18, 2013 at 19:22
  • Similar to Brocks comment, add a | ? {$_} to the end of the line. Commented Oct 20, 2015 at 3:21

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

-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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.