Break
suggest changeThe break operator will exit a program loop immediately. It can be used in For, ForEach, While and Do loops or in a Switch Statement.
$i = 0
while ($i -lt 15) {
$i++
if ($i -eq 7) {break}
Write-Host $i
}
The loop prints 1 through 6, then stops when $i becomes 7, before Write-Host runs.
Note: Inside ForEach-Object, break does not exit only that script block. It can stop the enclosing script. continue moves on to the next pipeline object. Prefer a foreach, while, or for loop when you need break.
Break Labels
Break can also call a label that was placed in front of the instantiation of a loop:
$i = 0
:mainLoop While ($i -lt 15) {
Write-Host $i -ForegroundColor 'Cyan'
$j = 0
While ($j -lt 15) {
Write-Host $j -ForegroundColor 'Magenta'
$k = $i*$j
Write-Host $k -ForegroundColor 'Green'
if ($k -gt 100) {
break mainLoop
}
$j++
}
$i++
}
Note: This code increments $i to 8 and $j to 13, which makes $k equal 104. Because $k exceeds 100, the code then breaks out of both loops.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents