If and Conditionals

View saved

if / elseif / else

Parentheses wrap the condition; braces wrap the body.

$freeGB = 12
if ($freeGB -lt 5) {
  Write-Output "Low disk"
} elseif ($freeGB -lt 20) {
  Write-Output "Getting full"
} else {
  Write-Output "Plenty of space"
}

Test paths

Common file checks before acting.

if (Test-Path .\practice\notes.txt) {
  Get-Content .\practice\notes.txt
} else {
  Write-Output "Missing notes.txt"
}

switch

Cleaner than long elseif chains for discrete values.

$role = "learner"
switch ($role) {
  "learner" { "Keep practicing" }
  "admin"   { "Double-check changes" }
  default   { "Unknown role" }
}

Boolean helpers

-not, -and, and -or combine tests. Prefer clear names over nested punctuation.

Comments

One comment per signed-in account. Comments are saved with this page’s URL.