Do…Loop
Definition: Repeats a block of statements while a condition
is
True
or until a condition becomes
True.
The preceding definition pretty much says it all: a Do While loop enables you to repeat a block of code over and over again, at least as long as a specified condition is true. By comparison, a Do Untilloop enables you to repeat a block of code over and over again, at least untila specified condition becomes true. As you might have guessed, you can create either type of loop using Windows PowerShell.
To begin with, let’s take a look at the Do While loop. To create a Do While loop you need the following items:
· The Dokeyword.
· The action (or actions) you want to perform. These actions must be contained within curly braces.
· The Whilekeyword.
· The condition that will spell the end of the loop. (In other words, when this condition is met then the loop should end.)
The following example assigns the value 1 to the variable $a, then uses that variable as part of a Do While loop. The action to be performed is fairly simple: we just echo back the value of $a, then use the ++operator to increment $a by 1. That’s what this portion of the code does:
{$a; $a++}
Meanwhile, we’ll keep the loop running as long as $ a isless than ( - lt) 10:
($a -
lt10)
Here’s the complete example:
$a = 1
And here’s what
you’ll get back if you execute those two lines of code:
1
The Do Until loop
is constructed the same way, except that we use the
Until
keyword instead of the While keyword. In this example, the
loop is designed to run until $
a isequal to (
-
eq) 10:
do {$a; $a++} while ($a -
lt10)
2
3
4
5
6
7
8
9