Conditionals: if, elseif, else
Prerequisites: Operators
$temperature = 18
if ($temperature -gt 25) {
'It is hot'
} elseif ($temperature -gt 15) {
'It is pleasant'
} else {
'It is cold'
}
It is pleasant
- The condition goes in parentheses; the code in braces.
- Only the first matching branch runs.
- Leaving a string on its own line outputs it — the same as
Write-Output.
What counts as true
Values are converted to $true or $false in conditions:
$tests = [ordered]@{
'0' = 0; '1' = 1; "''" = ''; "'text'" = 'text'
'$null' = $null; '@()' = @(); '@(0)' = @(0)
}
foreach ($test in $tests.GetEnumerator()) {
'{0,-8} -> {1}' -f $test.Key, [bool]$test.Value
}
0 -> False
1 -> True
'' -> False
'text' -> True
$null -> False
@() -> False
@(0) -> False
0, empty strings, $null, and empty arrays are false. Surprisingly, an
array containing a single 0 is also false, because PowerShell looks at
the one element. Test explicitly when it matters: if ($list.Count -gt 0).
if returns a value
$age = 20
$status = if ($age -ge 18) { 'adult' } else { 'minor' }
$status
adult
(In PowerShell 7, the ternary operator does the same: $age -ge 18 ? 'adult' : 'minor'.)
Practice
Store an age and output adult for 18 and over, teen for 13–17, and
child otherwise.
Show solution
$age = 15
if ($age -ge 18) { 'adult' }
elseif ($age -ge 13) { 'teen' }
else { 'child' }
teen