Understanding Booleans in PowerShell

Understanding Booleans in PowerShell

PowerShell supports a data type Boolean, with two values possible $true, and $false. In general, $false evaluates to 0 (zero), and $true evaluates to 1. And (usually) any non-zero integer evaluates as $true. But PowerShell does automatic data type-casting, based on the left side of the equation, leading to some interesting (and correct) behaviour.
 
So consider:
PS> 0 -eq $false     #As expected
True

PS>
-not 0              # As expected
True

PS>
1 -eq $true     #Still as expected
True

PS>
-not 1             # OK, I guess
False

PS>
$true -eq 2     # OK, that makes sense, since 2 is not zero.
True

PS>
2 -eq $true     # Hunh?
False
So, if $true is equal to 2, why isn’t 2 equal to $true? Because the method that PowerShell uses to evaluate an expression is determined by the left-most object, and this causes the right side of the equation to be cast to a the type of the leftmost object. So, in the expression $true -eq 2, what’s really happening is:
PS> [Bool]$true -eq [Bool]2
True

But when we switch sides of the expression, what we have is:
PS> [int]2 -eq [int]$true
False

And, sure enough, if we look at the integer value of $true, it’s 1 (one).
PS> [int]$true
1

This implicit casting happens all the time in PowerShell and (usually) helps make PowerShell behave the way you meant it to. But it can catch you off-guard if you’re not careful.
Sort by: Published Date | Most Recent | Most Useful
Comments
  • If you want to force PowerShell to check the input variable being of type Boolean and not accepting a 0 or 1, you can do this:

    $a = 1

    $a -eq $true

    returns True, which may not be what you want

    ($a.gettype() -eq $true.gettype()) -and ($a -eq $true)

    returns False if $a = 1, True if $a = $true

Page 1 of 1 (1 items)