PowerShell for Windows Admins

Feb 28 2014   4:44PM GMT

do and while

Richard Siddaway Richard Siddaway Profile: Richard Siddaway

Do you understand the difference between do loops and while loops?  On the surface they appear very similar.

£> do{$i++}while($i -lt 10) £> $i 10

£> $i=0 £> while($i -lt 10){$i++} £> $i 10

BUT there is a difference

£> $i=11 £> do{$i++}while($i -lt 10) £> $i 12

£> $i=11 £> while($i -lt 10){$i++} £> $i

Notice the difference in the final result

A DO loop will ALWAYS execute at least once because the test is at the end.

A while loop has the test at the beginning so may not execute at all.

I’ve seen this cause people real difficulty at times so think about where you need the test to be, if the loop needs to execute at least once and what the final value of any incrementing variables should be

 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.

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:

Share this item with your network: