PowerShell If / ElseIf / Else
Scripts constantly make decisions: does the file exist, is the disk almost full, did the command succeed? The if statement runs a block of code only when a condition is true.
$freeSpaceGB = 12
if ($freeSpaceGB -lt 20) {
"Warning: only $freeSpaceGB GB left"
}Warning: only 12 GB left
The condition goes in parentheses, the code in braces. Remember that PowerShell compares with -lt, -eq and friends, not < or ==.
Else and ElseIf
elseif tests further conditions in order; else runs when none of them matched. Only the first matching branch runs:
function Get-Grade([int]$Score) {
if ($Score -ge 90) {
'A'
} elseif ($Score -ge 80) {
'B'
} elseif ($Score -ge 70) {
'C'
} else {
'F'
}
}
foreach ($s in 95, 83, 70, 42) {
"$s -> $(Get-Grade $s)"
}95 -> A
83 -> B
70 -> C
42 -> F
Truthy and falsy values
The condition doesn't have to be a Boolean. PowerShell converts it, using these rules:
| Value | Treated as |
|---|---|
$false, 0, 0.0, '', $null |
false |
an empty array @() |
false |
| an array with one element | the truth of that element |
| any other number, string, array or object | true |
the string 'False' or '0' |
true (non-empty strings are true) |
$tests = [ordered]@{
'zero' = 0
'empty string' = ''
'text False' = 'False'
'null' = $null
'empty array' = @()
'array of 2' = @(0, 0)
}
foreach ($name in $tests.Keys) {
if ($tests[$name]) { "$name is truthy" } else { "$name is falsy" }
}zero is falsy
empty string is falsy
text False is truthy
null is falsy
empty array is falsy
array of 2 is truthy
This makes checks like if ($files) { … } (did the command return anything?) short and readable.
Combining conditions
Use -and, -or and -not to combine tests, and parentheses to group them:
$hour = 14
$isWeekend = $false
$onCall = $true
if (($hour -ge 9 -and $hour -lt 17 -and -not $isWeekend) -or $onCall) {
'Send the alert to the team'
}
$path = './settings.json'
if (-not (Test-Path $path)) {
"$path is missing, creating defaults"
}Send the alert to the team
./settings.json is missing, creating defaults
The ternary operator (PowerShell 7)
For a simple choice between two values, condition ? valueIfTrue : valueIfFalse is shorter than a full if:
$cpu = 87
$status = $cpu -gt 80 ? 'HIGH' : 'ok'
"CPU $cpu% is $status"
# Works in Windows PowerShell 5.1 too: an if statement used as an expression
$label = if ($cpu -gt 80) { 'HIGH' } else { 'ok' }
$labelCPU 87% is HIGH
HIGH
In PowerShell, if is also an expression: you can assign its result to a variable, which is the portable alternative to the ternary operator.
Common mistakes
if ($x = 5) { } # assigns 5 to $x (always true!) - use -eq
if ($x == 5) { } # error: == is not an operator in PowerShell
if ($x -eq 5) { } # correct
if ($list -eq $null) # filters the array - write ($null -eq $list)Tip: Use
switch(next lesson) instead of a longelseifchain when you compare one value against many possibilities.
Test yourself
Which branch runs for $n = 75 in if ($n -ge 90) {'A'} elseif ($n -ge 70) {'B'} elseif ($n -ge 50) {'C'}?
- A
- B
- B and C
- C
Is the string 'False' truthy or falsy in an if condition?
- Truthy
- Falsy
- It is an error
- It depends on culture
What is wrong with if ($count = 0) { ... }?
- Nothing
- It assigns 0 instead of comparing; use -eq
- Braces must be on a new line
- 0 cannot be compared