Skip to main content

How to Stop a Loop Early in PowerShell with break

· 3 min read
Jagdish Kumawat
Founder @ Dewiride

A loop doesn't always have to run to the end. Once you've found the item you were looking for, or hit a limit, break leaves the loop at once and carries on after it. This guide stops a loop over the numbers 1 to 10 at 4, with real output from PowerShell 7.6.10.

Syntax​

Syntax
foreach (<item> in <collection>) {
if (<condition>) {
break
}
<commands>
}
PartWhat it means
breakEnds the loop immediately. The commands after the loop run next
if (<condition>)Decides when to leave

The about_Break page: "The break statement provides a way to exit the current control block."

Prerequisites​

  • PowerShell 7. This guide uses PowerShell 7.6.10.

Step 1: Stop at Four​

1..10 is the numbers 1 to 10. The loop prints each one, but leaves when it reaches 4:

PowerShell
foreach ($number in 1..10) {
if ($number -eq 4) {
break
}
$number
}
Output
1
2
3

PowerShell running the foreach loop with break: it printed 1, 2 and 3.

At 4, break ran before the print, so the loop ended with 1, 2 and 3; the numbers 5 to 10 were never reached.

Common Mistakes​

MistakeWhat happensDo this instead
Using break to skip one itemThe whole loop endsUse continue: skipping 3 in 1 to 5 printed 1, 2, 4, 5
Putting break after the printThe item that triggered it is printed firstCheck the condition before the work you want to skip

Troubleshooting​

SymptomLikely causeFix
The loop stops sooner than expectedThe if condition is true earlier than you thoughtPrint the item before the if to see where it stops

FAQ​

What's the difference between break and continue?​

break ends the loop; continue ends only the current pass and goes on with the next item.

Does break work in while loops too?​

Yes. The about_Break page: "When a break statement appears in a loop, such as a foreach, for, do, or while loop, PowerShell immediately exits the loop." In a while ($true) loop, break stopped it with the counter at 3.

Conclusion​

break inside if ($number -eq 4) ended the loop after printing 1, 2 and 3. Use continue when you want to skip one item and keep going.

Additional Resources​