In Powershell, what does if($variable)
test for? Is this testing if the variable is set, is null, is true, or something else?
Powershell uses loose typing, and as a part of this any value can be used as a conditional expression. The logic of evaluating values to true or false (such values are often called "truthy" and "falsey") is in the System.Management.Automation.LanguagePrimitives.IsTrue function. The logic is the following:
$null
evaluates to false.$true
and $false
have their usual meaning.function Test
{
param ( [switch]$Option )
}
Test # $Option evaluates to false
Test -Option # $Option evaluates to true
# (Technically, $Option is not bool; it is of type SwitchParameter which,
# for almost all intents and purposes, can be used interchangeably with bool.)
IList
) uses the following logic: An empty collection is falsey; a collection with only one element evaluates to the truth value of its member; a collection with two or more elements is truthy.There are a couple of gotchas:
[System.Management.Automation.LanguagePrimitives]::IsTrue([char]0)
returns True (per the final clause); yet if([char]0) { "Truthy" } else { "Falsey" }
returns "Falsey". I wasn't able to find the reason why this happens.$array = New-Object -TypeName System.Object[] 1 # $array = new object[1]
$array[0] = $array
if($array) { "Truthy" } else { "Falsey" }
(The answer is: it crashes the process with StackOverflowException.)
It tests whether the variable is true or whether a non-Boolean variable can be coalesced to true. For example, each of these return false:
$var #uninitialized
$var = ""
$var = $false
$var = 0
Each of these return true:
$var = "something"
$var = $true
$var = 1 #or any non-zero number