PowerShell for Windows Admins

Jun 29 2016   8:36AM GMT

Boolean in Where-Object filter

Richard Siddaway Richard Siddaway Profile: Richard Siddaway


I was testing some code yesterday and realised there was a quirk in the way the original where syntax (with {}) worked and the way the newer syntax worked.

To demonstrate this I created a set of objects

$i = 0

$tests = while ($i -lt 25){
New-Object -TypeName PSObject -Property @{
Index = $i
Current = if (-not($i % 2)){$true} else {$false}

Object properties are a numeric index and a boolean value

If you want just the $true values many people write this

$tests | where {$_.Current -eq $true}

or if using the newer syntax use this

$tests | where Current -eq $true

This is unnecessary typing as you can do this

$tests | where {$_.Current}

$tests | where Current

The reason is that the filter you are creating tests a property of the current object against your criteria and passes is if the result is true. A boolean property will by definition either be true of false so just need to test directly

if you want to double negative type test i.e. – not $true (which I don’t recommend as its very easy to get into  logic mess) then you have to do this

$tests | where {-not $_.Current}

as this fails
$tests | where –not Current

You could do this

$tests | where Current -ne $true

but it negates the whole code simplification objective

 Comment on this Post

There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to:

Share this item with your network: