๐
Loops & Conditionals
Iterate over collections and branch on conditions.
Looping
Loop over a collection (pipeline)
Run a block for each item coming down the pipeline.
1..5 | ForEach-Object { Write-Host "Number $_" }foreach statement
Classic loop over an array.
$names = @("Ann", "Bob", "Cy")
foreach ($name in $names) {
Write-Host "Hello $name"
}while loop
Repeat while a condition holds.
$i = 0
while ($i -lt 3) {
Write-Host $i
$i++
}for loop
Counter-based loop.
for ($i = 0; $i -lt 3; $i++) {
Write-Host "Step $i"
}Conditionals
if / elseif / else
Branch on comparison operators.
$n = 7
if ($n -gt 10) {
"big"
} elseif ($n -gt 5) {
"medium"
} else {
"small"
}switch statement
Match a value against several cases.
switch ($env:OS) {
"Windows_NT" { "Running on Windows" }
default { "Other OS" }
}Filter with Where-Object
Keep only items matching a condition.
Get-Process | Where-Object { $_.CPU -gt 100 }