← PowerShell course
4

Loops & Logic

30 min

Master 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.

By the end you can
  • 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.

OperatorMeaning
-eqEqual
-neNot equal
-lt / -leLess than / less than or equal
-gt / -geGreater than / greater than or equal
-likeWildcard match (*, ?)
-matchRegex 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 immediately
  • continue — 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"
}