The syntax for a While loop is this:
While(
) {
}
Notice how much simpler it is than a For loop. To compare the two, the following
code snippet shows how we can use a While loop to have our script count from 1 to
100:
$i = 1
while($i -lt 101) {
write-host $i
$i++
}
The Do??¦While statement is an interesting variation of the While loop in that just
like the While loop, it loops through a code block while a condition is true. The main
differentiator is that since the condition is checked at the end of the code block, every Do
loop is guaranteed to execute at least once. Consider the following example:
$a = 11
do {
write-host $a
450 Microsoft Windows Server 2008 Administration
$a++
} while ($a -lt 10)
write-host "Done!"
Notice how you initialized the $a variable to the value of 11. This is already greater
than the condition for the loop, which is set to run only while $a is less than 10. If you
run this code snippet, you will see the output of 11 followed by the string Done! As you
can see, since the while condition is at the end of the block, it isn??™t evaluated until after
the block has executed at least once. In this case, the value of $a was already displayed
before the while condition was checked and the loop terminated immediately due to
the value of $a being too great.
A typical example for a scenario where a Do??¦While loop would be appropriate is
when prompting the user for some information.
Pages:
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480