PowerShell for Windows Admins

Mar 18 2014   3:34PM GMT

Continue please

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

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

 Comment on this Post

 
There was an error processing your information. Please try again later.
Thanks. We'll let you know when a new response is added.
Send me notifications when other members comment.

REGISTER or login:

Forgot Password?
By submitting you agree to receive email from TechTarget and its partners. If you reside outside of the United States, you consent to having your personal data transferred to and processed in the United States. Privacy

Forgot Password

No problem! Submit your e-mail address below. We'll send you an e-mail containing your password.

Your password has been sent to: