PowerShell Loops
Loops repeat code. PowerShell has five kinds: foreach for every item of a collection, for with a counter, while and do/until for conditions, and the ForEach-Object cmdlet for pipelines (next lesson).
| Loop | Use when |
|---|---|
foreach ($x in $list) { } |
you have a collection in memory |
for ($i = 0; $i -lt 10; $i++) { } |
you need an index or a step |
while (cond) { } |
repeat while a condition holds (may run 0 times) |
do { } while (cond) / do { } until (cond) |
run at least once |
… | ForEach-Object { } |
process pipeline input as it streams |
foreach
$services = 'nginx', 'postgres', 'redis'
foreach ($service in $services) {
"Checking $service..."
}
$total = 0
foreach ($n in 1..100) { $total += $n }
"Sum of 1..100 = $total"Checking nginx...
Checking postgres...
Checking redis...
Sum of 1..100 = 5050
The loop variable ($service) takes each value in turn. foreach loads the whole collection first, which makes it fast for data you already have.
for
The for loop has three parts: initialisation, condition and step.
for ($i = 1; $i -le 5; $i++) {
"Line $i of 5"
}
$letters = 'a', 'b', 'c', 'd', 'e', 'f'
for ($i = 0; $i -lt $letters.Count; $i += 2) {
"index $i = $($letters[$i])"
}Line 1 of 5
Line 2 of 5
Line 3 of 5
Line 4 of 5
Line 5 of 5
index 0 = a
index 2 = c
index 4 = e
while and do
while checks the condition before each pass; do … while and do … until check it after, so their body always runs at least once:
$balance = 1000
$years = 0
while ($balance -lt 2000) {
$balance *= 1.07
$years++
}
"Doubled after $years years: $([math]::Round($balance, 2))"
$attempt = 0
do {
$attempt++
"attempt $attempt"
} until ($attempt -ge 3)Doubled after 11 years: 2104.85
attempt 1
attempt 2
attempt 3
until runs until the condition becomes true; while runs while it is true. A classic use of do … until is retrying an operation until it succeeds or a limit is reached.
break and continue
continue skips the rest of the current pass; break leaves the loop entirely:
foreach ($n in 1..10) {
if ($n % 2 -eq 0) { continue } # skip even numbers
if ($n -gt 7) { break } # stop after 7
"odd: $n"
}odd: 1
odd: 3
odd: 5
odd: 7
To leave an outer loop from inside an inner one, give the outer loop a label and name it in break:
$grid = @(
@(3, 8, 1),
@(4, 42, 9),
@(7, 5, 6)
)
:rows foreach ($row in 0..2) {
foreach ($col in 0..2) {
if ($grid[$row][$col] -eq 42) {
"Found 42 at row $row, column $col"
break rows
}
}
}
'search finished'Found 42 at row 1, column 1
search finished
Collecting loop output
Everything a loop body outputs can be captured. This is the idiomatic (and fast) way to build an array:
$squares = foreach ($n in 1..5) { $n * $n }
$squares -join ', '
$evens = for ($i = 0; $i -le 10; $i += 2) { $i }
$evens.Count1, 4, 9, 16, 25
6
Warning: In an endless
while ($true)loop, make sure some path reachesbreak. In the console, Ctrl+C stops a runaway loop.
Test yourself
Which loop always runs its body at least once?
- foreach
- for
- while
- do ... until
What does continue do in a foreach loop?
- Exits the loop
- Skips to the next item
- Restarts the loop
- Pauses the script
How do you exit an outer loop labelled :outer from an inner loop?
- exit outer
- break outer
- return outer
- continue