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

This entry was posted in Powershell Basics. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s