Breaking and continuing
The break
and continue
statements are related and allow us to control how our loops behave. We can also use them in switch
statements. It’s important not to use them outside of loops or switch
statements as they can lead to unpredictable behavior. A break
statement can be used to stop a loop iterating altogether, while continue
can be used to stop an iteration and move on to the next one. Let’s look at break
first.
The break statement
Let’s play with the trusty while
loop. Type this:
$number = 0 while ( $number -ne 5) { $number ++ if ($number -eq 3) { break } Write-Host "The number is $number" }
Hopefully, you’ll see that the last number printed is 2
. The conditional if
statement says to stop looping if $number
is 3
. The break
statement only acts on the loop it is nested inside.
The continue statement
The continue
statement stops the...