header image

Boolean in Where-Object filter

Posted by: | June 29, 2016 Comments Off on Boolean in Where-Object filter |

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

under: PowerShell Basics

Comments are closed.