If the code within the loop is designed
to display the prompt, process the input, and then compare it against a certain value (for
example, if you are prompting for a password), then a Do??¦While loop guarantees that
the prompt will be displayed at least once. It also makes sense to do this since you obviously
have nothing to compare against until the user has entered some information, so
all the other looping constructs would be inefficient since they want to evaluate a condition
before even getting any information from the user.
Finally, two other statements are very important to loops: break and continue statements.
The break statement is a way to completely bypass any other condition for the
loop and instruct Windows PowerShell to get out of the loop right away (kind of like the
???Go to Jail, Do Not Pass Go??? card in your favorite board game). The continue statement
is slightly different in that it instructs Windows PowerShell to stop processing the rest of
the code in the code block and immediately jump to the next iteration of the loop.
Let??™s see these in practice. The following example shows how break and continue
statements can be used to perform flow control within a loop:
$a = 0
write-host "Starting to count to 10??¦"
while ($a -lt 11) {
$a++
if ($a -eq 3) {
continue
}
if ($a -eq 8) {
break
}
write-host $a
}
write-host "Done!"
In this code, we are trying to count from 1 to 10 with a twist.
Pages:
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481