Watch out those PowerShell Boolean Objects

Comparing a Boolean object [bool] to any non-null string will always return True. This is due to type conversion in action where the right-hand item is silently converted to match that on the left-hand side (”best effort”). To avoid surprises, always verify the object type before making a one-to-one comparison.

Take for example:

PS C:\> $status = $true
PS C:\> $status -eq “true”
True

PS C:\> $status -eq “false”
True

PS C:\> $status -eq “1″
True

PS C:\> $status -eq “0″
True

PS C:\> $status.gettype()

IsPublic IsSerial Name BaseType
——– ——– —- ——–
True True Boolean System.ValueType

To make sure that comparison works as as expected, always compare it to the same Boolean object type or the numeric equivalent:

PS C:\> $status -eq $null
False

PS C:\> $status -eq $true
True

PS C:\> $status -eq $false
False

PS C:\> $status -eq 1
True

PS C:\> $status -eq 0
False

No Comments »

Trackback URI | Comments RSS

Leave a Reply

You must be logged in to post a comment.