TExcelTAD
Home › PowerShell › PowerShell If / ElseIf / Else

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.

powershell · try it yourself
$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:

powershell · try it yourself
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)
powershell · try it yourself
$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:

powershell · try it yourself
$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:

powershell · try it yourself
$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' }
$label
CPU 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

text
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 long elseif chain 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'}?

  1. A
  2. B
  3. B and C
  4. C

Is the string 'False' truthy or falsy in an if condition?

  1. Truthy
  2. Falsy
  3. It is an error
  4. It depends on culture

What is wrong with if ($count = 0) { ... }?

  1. Nothing
  2. It assigns 0 instead of comparing; use -eq
  3. Braces must be on a new line
  4. 0 cannot be compared