PowerShell Loop Control
Loop control is the use of break and continue inside a loop. Break stops a loop at once, and continue skips to the next pass.
Stop early with break
Break ends the loop the moment it runs. Here the loop never reaches the larger numbers.
foreach ($n in 1..10) {
if ($n -gt 3) { break }
$n
}Skip one item with continue
Continue skips the rest of the pass. Here the number 3 never prints, but the loop keeps going.
foreach ($n in 1..5) {
if ($n -eq 3) { continue }
$n
}Break out of a while loop
A while loop with a true condition runs until something stops it. Break gives it that exit.
$n = 0
while ($true) {
$n = $n + 1
if ($n -eq 3) { break }
$n
}Example
foreach ($n in 1..10) {
if ($n % 2 -eq 0) { continue }
if ($n -gt 5) { break }
$n
}Key points
- Break: a keyword that ends the loop it sits in at once.
- Continue: a keyword that skips the rest of the current pass and starts the next pass.
- Use break when you have found what you were looking for and no more passes are needed.
- Use continue when one item should be skipped but the loop should keep going.
- Break and continue work inside foreach, for, and while loops.
In this example, the loop walks the numbers 1 through 10. Even numbers are skipped by continue, and the loop stops by break once a number passes 5. Only the odd numbers up to 5 print.
Note
break ends the whole loop, while continue ends only the current pass.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does this script print? foreach ($n in 1..5) { if ($n -eq 2) { continue }; $n }