Converting VBScript's Do...Loop Statement

Definition: Repeats a block of statements while a condition is True or until a condition becomes True.

Do…Loop

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 Until loop enables you to repeat a block of code over and over again, at least until a 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 Do keyword.

  • The action (or actions) you want to perform. These actions must be contained within curly braces.

  • The While keyword.

  • 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 is less than (-lt) 10:

($a -lt 10) 

Here’s the complete example:

$a = 1
do {$a; $a++} while ($a -lt 10)

And here’s what you’ll get back if you execute those two lines of code:

1
2
3
4
5
6
7
8
9

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 is equal to (-eq) 10:

$a = 1
do {$a; $a++} until ($a -eq 10)

And here’s what you’ll get back if you execute these two lines of code:

1
2
3
4
5
6
7
8
9

Return to the VBScript to Windows PowerShell home page