A Quick Lesson in Boolean

I often see scripts that are checking for True/False values using an If/Else statement like the one below.

if($value){
    'True'
} else { 
    'False'
}

While this technically will work for Boolean values, there are situations where this will not work. For example, if you pass the string value of “False” to the statement above it will evaluate as True. This is because the if condition in that code is not checking for True, it is checking for if exists. In that statement anything that is not Boolean False, Null, an empty string, or 0 will return True. However, if you specify a value must be true or false, PowerShell will auto-convert things like the string equal to ‘False’ as actually being false.

This is why I always recommend using the full condition of if($value -eq $true). Not only will this give you the ability to account for variables you may not be able to control, it also gives you a way to handle non-Boolean values. You can test it out for yourself using the snippet below, and see how the different ways of writing this If/Else statement work out.

Function Test-Boolean($value, $test){
    if($value -eq $true){
        $Result='True'
    } elseif ($value -eq $false) { 
        $Result='False'
    } else {
         $Result='Else'
    }

    if($value){
        $IfElse = 'True'
    } else { 
        $IfElse = 'False'
    }

    [pscustomobject]@{TrueFalse=$Result;IfElse=$IfElse;Value=$value;Test=$test}
}


Test-Boolean $true 'True boolean'
Test-Boolean 'true' 'True string'
Test-Boolean 1 '1 integer'
Test-Boolean $false 'False boolean'
Test-Boolean 'false' 'False string'
Test-Boolean 0 '0 integer'
Test-Boolean 'random' 'Any other string'
Test-Boolean 2 'Any other integer'
Test-Boolean ([string]::Empty) 'Empty string'
Test-Boolean ' ' 'Blank string'
Test-Boolean $null 'Null value'

After you run the snippet you should see results like the one below showing you how the two different If/Else statements evaluated the different values.