break

verb

say it: “BRAYK” /ˈbreɪk/

A command that stops a loop at once, so the script goes on with whatever comes after the loop.

What does break do in a PowerShell loop?

break leaves a loop at once, and the script carries on with the first line after the loop's closing brace. It belongs to foreach, for, while and do; inside ForEach-Object's braces it stops the whole line or script instead.

$total = 0
foreach ($song in Import-Csv playlist.csv) {
    if ($total + [int]$song.Minutes -gt 20) { break }
    $total += [int]$song.Minutes
}
"$total of 20 minutes"
# 18 of 20 minutes

In a sentence

  • “Sam used break to leave the loop the moment the retry worked.”
  • “The playlist loop hits break when the next song would go past 20 minutes.”

Level: Apprentice · More PowerShell terms at this level

Updated

In other subjects