Categories

Continue please

I needed to be able to skip processing in a loop and remembered that the continue command suspends the loop processing and immediate goes back to the top of the loop. I thought a quick look at how it works in different types of loop would be worthwhile.

These all work and produce the same output

1

2

3

5

6

 

FOR loop

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

 

WHILE loop

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

 

DO loop

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

 

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

 

FOREACH loop

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

 

THIS NEXT ONE WON’T WORK

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

 

You will terminate the pipeline by using continue.

One way to do this would be:

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

 

Continue is a useful trick that gives you more control within the loop

One Response to Continue please

  • James Brown says:

    Thanks for putting all these in one place, as I often forget which command does what. “Continue” often seems counter-intuitive to me, as I would expect it would, well, continue with the next command within the command block rather than stop everything and go back to the top of the loop. The script isn’t ‘continuing’ anything; it’s doing an about-face.

    Or so it seems to me.

Leave a Reply