Loops
Prerequisites: Arrays
PowerShell has several loops. You'll use foreach and ForEach-Object
most.
foreach — loop over a collection
$fruits = 'apple', 'banana', 'cherry'
foreach ($fruit in $fruits) {
"I like $fruit"
}
I like apple
I like banana
I like cherry
ForEach-Object — loop in a pipeline
1..3 | ForEach-Object { "Pass $_" }
'ada', 'linus' | ForEach-Object { $_.ToUpper() }
Pass 1
Pass 2
Pass 3
ADA
LINUS
foreach (the statement) works on a collection already in memory and is
faster; ForEach-Object (the cmdlet) processes objects as they flow
through a pipeline, one at a time — better for very large or streaming
input.
for, while, do
for ($i = 10; $i -gt 0; $i -= 3) {
$i
}
$balance = 100
$months = 0
while ($balance -lt 200) {
$balance *= 1.1
$months++
}
"Doubled after $months months"
$attempt = 0
do {
$attempt++
"Attempt $attempt"
} until ($attempt -ge 2)
10
7
4
1
Doubled after 8 months
Attempt 1
Attempt 2
for— a counting loop.while— repeats while the condition is true (checked first).do { } while (...)/do { } until (...)— checks after each pass, so the body runs at least once.
break and continue
foreach ($n in 1..10) {
if ($n % 2 -eq 0) { continue }
if ($n -gt 7) { break }
$n
}
1
3
5
7
Common mistakes
- Using
continueorbreakinsideForEach-Object— they don't skip one item; they end the whole script block pipeline (or even the script). InForEach-Object, usereturnto skip to the next object.
Practice
Print the 5 times table from 5 x 1 = 5 to 5 x 10 = 50.
Show solution
foreach ($n in 1..10) {
"5 x $n = $(5 * $n)"
}
5 x 1 = 5
5 x 2 = 10
5 x 3 = 15
5 x 4 = 20
5 x 5 = 25
5 x 6 = 30
5 x 7 = 35
5 x 8 = 40
5 x 9 = 45
5 x 10 = 50