Categories

Give me a break

Having shown how to use continue last time I thought I’d show the opposite functionality this time and demonstrate how to jump out of a loop.

You do this using the break command.  The following examples show how it works. What do you think the output of these loops will be?

FOR loop

for ($i=1; $i -le 6; $i++){
  if ($i -eq 4) {break}
  $i
}

WHILE loop

$i = 0
while ($i -lt 6){
$i++
if ($i -eq 4) {break}
$i
}

DO loop

$i = 0
do {
$i++
if ($i -eq 4) {break}
$i
} while ($i -lt 6)

$i = 0
do {
$i++
if ($i -eq 4) {break}
$i
} until ($i -ge 6)

FOREACH loop

$numbers = 1..6
foreach ($number in $numbers) {
if ($number -eq 4) {break}
$number
}

If you said the output would be

1

2

3

You were correct.

THIS NEXT ONE WILL WORK

1..6 |
foreach {
if ($psitem -eq 4) {break}
$psitem
}

Though you want to think carefully before terminating a pipeline like this. 

Leave a Reply