PowerShell Loops Break


Example

The 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 above will count to 15 but stop as soon as 7 is reached.

Note: When using a pipeline loop, break will behave as continue. To simulate break in the pipeline loop you need to incorporate some additional logic, cmdlet, etc. It is easier to stick with non-pipeline loops if you need to use 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 will increment $i to 8 and $j to 13 which will cause $k to equal 104. Since $k exceed 100, the code will then break out of both loops.