0
0
PowerShellscripting~5 mins

Break and continue in PowerShell

Choose your learning style9 modes available
Introduction

Break and continue help control loops. Break stops the loop early. Continue skips to the next loop round.

Stop searching when you find what you want in a list.
Skip processing items that don't meet a condition.
Exit a loop if an error happens.
Ignore certain values but keep looping.
Improve script speed by stopping unnecessary work.
Syntax
PowerShell
break
continue

break exits the nearest loop immediately.

continue skips the rest of the current loop and starts the next iteration.

Examples
This loop stops completely when $i equals 3.
PowerShell
foreach ($i in 1..5) {
  if ($i -eq 3) { break }
  Write-Output $i
}
This loop skips printing 3 but continues with 4 and 5.
PowerShell
foreach ($i in 1..5) {
  if ($i -eq 3) { continue }
  Write-Output $i
}
Sample Program

This script loops from 1 to 6. It skips printing number 4 and stops the loop when it reaches 6.

PowerShell
foreach ($number in 1..6) {
  if ($number -eq 4) {
    Write-Output "Skipping number 4"
    continue
  }
  if ($number -eq 6) {
    Write-Output "Stopping at number 6"
    break
  }
  Write-Output "Number: $number"
}
OutputSuccess
Important Notes

Use break carefully to avoid stopping loops too early.

Continue is useful to skip unwanted cases without stopping the whole loop.

Summary

break stops the loop immediately.

continue skips to the next loop iteration.

Both help make loops smarter and more efficient.