header image

do and while

Posted by: | February 28, 2014 | No Comment |

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

under: PowerShell Basics