PSPowerShell · Lesson 3 of 8

Control Flow

PowerShell control flow is standard C-family with a few extras. The switch statement is particularly powerful — it can match regexes and wildcards.

PowerShell
# if / elseif / else
$score = 85

if ($score -ge 90) {
    Write-Host "A"
} elseif ($score -ge 80) {
    Write-Host "B"
} elseif ($score -ge 70) {
    Write-Host "C"
} else {
    Write-Host "Below C"
}

# Comparison operators (different from most languages!)
# -eq   equal
# -ne   not equal
# -gt   greater than
# -lt   less than
# -ge   greater than or equal
# -le   less than or equal
# -like wildcard match   ("hello" -like "h*")
# -match regex match     ("hello123" -match "d+")
# -contains array contains
# -in   value in array

$name = "Alice"
if ($name -like "A*") { Write-Host "Starts with A" }
if ($name -match "^[A-Z]") { Write-Host "Starts with uppercase" }
if ("red" -in @("red", "green", "blue")) { Write-Host "Color found" }

# Ternary (PowerShell 7+)
$result = $score -ge 60 ? "Pass" : "Fail"
PowerShell
# switch — very powerful in PowerShell
$day = "Monday"
switch ($day) {
    "Saturday" { Write-Host "Weekend!"; break }
    "Sunday"   { Write-Host "Weekend!"; break }
    default    { Write-Host "Weekday" }
}

# switch with -Wildcard
switch -Wildcard ("hello123") {
    "hello*"  { Write-Host "Starts with hello" }
    "*123"    { Write-Host "Ends with 123" }
}

# switch with -Regex
switch -Regex ("192.168.1.1") {
    "^d{1,3}.d{1,3}" { Write-Host "Looks like an IP" }
}

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

# foreach loop — most common
$fruits = @("apple", "banana", "cherry")
foreach ($fruit in $fruits) {
    Write-Host $fruit
}

# ForEach-Object — pipeline version
1..5 | ForEach-Object { Write-Host "Item: $_" }

# Where-Object — filter pipeline
Get-Process | Where-Object { $_.CPU -gt 10 } | Select-Object Name, CPU

# while loop
$n = 10
while ($n -gt 0) {
    Write-Host $n
    $n -= 3
}