Skip to content

Control Flow

Scope: if, loops, foreach, and switch. All examples were run with PowerShell 7.5.

if / elseif / else

$age = 20
if ($age -ge 18) {
    Write-Host "adult"
} elseif ($age -ge 13) {
    Write-Host "teenager"
} else {
    Write-Host "child"
}

Comparison operators are words, not symbols:

Operator Meaning
-eq -ne Equal / not equal
-gt -ge -lt -le Greater/less than (or equal)
-like -notlike Wildcard match (*, ?)
-match -notmatch Regex match
if ($name -like "A*") { Write-Host "starts with A" }

Case-insensitive by default; prefix with c for case-sensitive: -ceq, -clike, -cmatch.

Gotcha: = is assignment. if ($x = 5) assigns 5 and is always true. You want -eq.

foreach: two forms

# Statement — over a collection you already have
foreach ($n in 1..5) {
    Write-Host $n
}

# Cmdlet — in a pipeline, $_ is the current object
1..5 | ForEach-Object { Write-Host $_ }

1..5 is the range operator (1 through 5). Use the statement form for readability; the cmdlet form inside pipelines.

for and while

for ($i = 0; $i -lt 5; $i++) {
    Write-Host $i
}

$n = 1
while ($n -lt 100) {
    $n *= 2
}

Same shapes as other languages, word-operators aside.

switch

$day = "Sat"
switch ($day) {
    { $_ -in "Sat", "Sun" } { "weekend"; break }
    "Mon"                   { "back to work"; break }
    default                 { "weekday" }
}

PowerShell switch matches every case unless you break — it doesn't stop at the first match like most languages. The { } form lets you use any condition. Add -Regex or -Wildcard after switch for pattern matching modes.

break and continue

Work as expected in loops. In switch, break exits the whole switch; continue moves to the next case (rarely what you want — prefer break).

Ternary and null-coalescing (PS 7+)

$label = $age -ge 18 ? "adult" : "minor"
$city = $user.City ?? "unknown"

The ternary ? : and ?? ("use the right side if the left is $null") are PowerShell 7+ only — they don't exist in Windows PowerShell 5.1. Another reason to use 7.

Check

  • [ ] You use -eq etc. and never = in a condition
  • [ ] You can write both foreach forms and pick correctly
  • [ ] You know switch needs break to stop matching

Next: Functions.