Watch out those PowerShell Boolean Objects
Jul 26th 2007Desmond LeePowerShell
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”
TruePS C:\> $status -eq “false”
TruePS C:\> $status -eq “1″
TruePS C:\> $status -eq “0″
TruePS 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
FalsePS C:\> $status -eq $true
TruePS C:\> $status -eq $false
FalsePS C:\> $status -eq 1
TruePS C:\> $status -eq 0
False
No Comments »
Leave a Reply
You must be logged in to post a comment.