PoshBytes: Is That Really False?
A quick look at why if($value) is not always the same as checking for true or false in PowerShell. Learn how PowerShell treats strings, numbers, and nulls in Boolean checks so your logic does not wander off and join the circus.
This post is a companion for the video embedded below. Scroll down to see the code from the video.
if($value) is not the same as Boolean logic
function IsTrue($value){
if($value){
"$value is True"
} else {
"$value is False"
}
}
IsTrue $true
IsTrue $false
IsTrue 'true'
IsTrue 'false'
Running the code below will show that the string 'false' is actually evaluated by true.
But Why?
Using the function below you can see how explicitly checking Boolean is different than just checking it is something.
Function Test-Boolean($value){
if($value -eq $true){
Write-Host "'$value' is true" -Fore Green
}
if ($value -eq $false) {
Write-Host "'$value' is false" -Fore Yellow
}
if ($value) {
Write-Host "'$value' is something" -Fore Cyan
}
if (-not $value) {
Write-Host "'$value' is nothing" -Fore Red
}
}
Test-Boolean $true
Test-Boolean 'true'
Test-Boolean 1
Test-Boolean $false
Test-Boolean 'false'
Test-Boolean 0
Test-Boolean 'random'
Test-Boolean 2
Test-Boolean ' '
Test-Boolean ([string]::Empty)
Test-Boolean $null
Wrap Up
• if($value) checks for truthy or falsy values, not strict Boolean meaning
• Non-empty strings like ‘false’ still evaluate as true in a plain if($value) check
• Explicit comparisons like -eq $true and -eq $false are safer when input may not be a real Boolean
• Testing different data types is the fastest way to understand PowerShell condition behavior