Loops & Logic
30 minMaster PowerShell's control-flow toolkit — conditionals, switch statements, and every loop construct — so you can automate server checks, retries, and bulk operations across your fleet.
- ▸Use comparison operators and combine conditions with -and, -or, and -not
- ▸Write if / elseif / else branches to act on disk, service, or environment state
- ▸Use switch to dispatch cleanly on environment or status strings
- ▸Iterate over server arrays with foreach and process each result
- ▸Build a while-based retry loop with a counter and break/continue
Comparison Operators
PowerShell's comparison operators return $true or $false.
| Operator | Meaning |
|---|---|
-eq | Equal |
-ne | Not equal |
-lt / -le | Less than / less than or equal |
-gt / -ge | Greater than / greater than or equal |
-like | Wildcard match (*, ?) |
-match | Regex match |
if / elseif / else
Branch on any Boolean expression:
$freePercent = 12
if ($freePercent -lt 10) {
Write-Host "CRITICAL: disk nearly full" -ForegroundColor Red
} elseif ($freePercent -lt 20) {
Write-Host "WARNING: disk low" -ForegroundColor Yellow
} else {
Write-Host "OK: disk healthy" -ForegroundColor Green
}
Combining Conditions
Use -and, -or, and -not to build compound tests:
if ($cpuPct -gt 90 -and $memFreeMB -lt 512) {
Write-Host "Server under pressure"
}
switch
switch is cleaner than a long if / elseif chain when you are testing one value against several patterns:
$env = "Prod"
switch ($env) {
"Prod" { Write-Host "Deploying to Production — change window required" }
"UAT" { Write-Host "Deploying to UAT" }
"Dev" { Write-Host "Deploying to Dev — no approval needed" }
default { Write-Host "Unknown environment: $env" }
}
foreach
The most common loop in sysadmin scripts — iterate over a collection:
$servers = @("SRV-WEB01", "SRV-WEB02", "SRV-DB01")
foreach ($server in $servers) {
Write-Host "Checking $server..."
}
for and while
for is ideal when you need a counter; while runs until a condition becomes false — perfect for polling or retries:
$attempt = 0
$maxAttempts = 3
while ($attempt -lt $maxAttempts) {
$attempt++
Write-Host "Attempt $attempt of $maxAttempts"
break
}
break and continue
break— exit the loop immediatelycontinue— skip the rest of the current iteration and move to the next
foreach ($server in $servers) {
if ($server -eq "SRV-DECOM") { continue }
Write-Host "Processing $server"
}Quick check
In this lab you will build five short scripts that mirror real desktop-support and server-administration tasks. Each step introduces one control-flow construct; the final step combines them into a realistic fleet health check.
if / elseif / else
You have measured a server's disk and stored the free-space percentage in $freePercent. Print a status line depending on how critical it is: below 10 is CRITICAL, below 20 is WARNING, otherwise OK. The starter sets $freePercent = 14.