Break

Exit a program loop immediately.

Break can also be used to stop script execution when it is placed outside a loop or switch statement.

In a For, ForEach, While, Do loop or in a Switch statement you can add a break statement to exit each code block.

Choose the conditions under which you call the continue statement carefully, as it is easy to create an infinite loop. Most commonly an if statement can be used to define the break conditions.

Examples

Count to 10 but stop as soon as you reach number 5:

 PS> $i = 0
 PS> while ($i -lt 10) {
        $i +=1 
        if ($i -eq 5) {break}
        Write-Host $i
     }

In a switch statement, break tells switch to stop looking further, in other words "you have a match, so no need to perform the other tests."

$department = "sales"

switch ($department) {
   "HR" {echo "HR found"; break}
   "sales" {echo "found sales"; break}
   "engineering" {echo "found engineering"; break}
}

“Our greatest glory is not in never failing, but in rising up every time we fail” ~ Ralph Waldo Emerson

Related:

Continue - Skip just this iteration of a loop
Exit-PSSession - Exit PowerShell (or exit a script)
Return - Exit the current scope, (function, script, or script block).
Trap - Handle a terminating error
While - Loop while a condition is True


Copyright © SS64.com 1999-2017
Some rights reserved