So far, we have relied on the conditional logic of loops to exit the iterations. Sometimes we want to exit the loop early or skip an iteration. This is what the break
and continue
commands are for.
break
will exit the loop it is executed in:
for ($i = 0; $i -lt 5; $i++) { if ($i -eq 2) { break } Write-Host $i }
The above for
loop is defined to loop 5 times: $i
starts at 0, and each loop will fire from $i
equals 0
through 4
. Inside the loop body is an if
statement that checks if $i
is 2
, and if so, break
. The following output shows that the loop exits once $i
equals 2
.
0 1
continue
will skip a loop iteration:
for ($i = 0; $i -lt 5; $i++) { if ($i -eq 2) { continue } Write-Host $i }
Using the first example but replacing break
with continue
causes the loop to finish through the condition, $i -lt 5
, but skip the iteration when $i
equals 2
. The output shows this:
0 1 3 4
As we can see, the for
loop finishes its iterations but does not output 2
.
break
and continue
are helpful when there are exceptional cases that need to be considered when looping. Your loop condition may cover some or most situations for your code execution, but break
and continue
can add extra behavior if necessary.
Instructions
In BREAK_Example.ps1, the while
loop outputs 1
through 5
.
Insert the correct command inside the if ($count -eq 3)
body so the loop only outputs 1
and 2
.
In BREAK_Example.ps1, the for
loop outputs 0
through 9
.
Insert the correct command inside the if ($i % 2 -eq 0)
body so the loop only outputs odd numbers.
In BREAK_Example.ps1, the switch
statement outputs both: Greater than 5
and Greater than 0
.
Insert the correct command inside the {$_ -gt 5}
body so Greater than 5
.
Once complete, try the other possible command to see if that works too.