While vs Do-While in PowerShell

3 minute read

One of the basics of PowerShell that is often overlooked (I say that because I often overlook it) is the difference between the While loop and the Do-While loop. It is a straightforward difference, so I won’t waste your time with too much commentary here.

The loops

While

The While loop in PowerShell will evaluate a conditional statement and only enter the While loop if the statement returns true. Here’s a very simple example:

$x = 0
while ($x -lt 10) {
    $x
    $x++
}

The first thing that happens here is that the conditional statement is evaluated. If $x is less than 10, then the loop will run. We can see on the previous line that $x equals 0, so the loop will run. Then each time the loop runs, $x is incremented and the loop will run a total of 10 times outputting 0 through 9. When $x gets up to 10, then the loop will not run and the script would continue on.

The important thing to note is that in a While loop the conditional statement runs first.

Do-While

Conversely, the Do-While loop in PowerShell will run the loop first and then evaluate the While conditional statement. Here’s the same example, but reworked as a Do-While loop:

$x = 0
Do {
    $x
    $x++
} while ($x -lt 10)

And in this case, the output is going to be exactly the same. The difference is how it operates. The Do loop will run first, then, after each run, the while statement is evaluated to see if $x is still less than 10. If it is not, then it exits the loop.

The difference

Lets look at a loop that will actually operate differently. Lets say that $x is equal to 11. How will the loops behave differently?

Here is the While loop:

$x = 11
while ($x -lt 10) {
    $x
    $x++
}

In this case, the While loop will not ever run. It will evaluate the conditional statement and realize that $x is not less than 10 and the loop will not run.

Here is the Do-While equivalent:

$x = 11
Do {
    $x
    $x++
} while ($x -lt 10)

In this case, the Do loop will run the first time before the conditional While statement is evaluated and finds that $x is not less than 10. So at the end of this, $x will be 12 instead of 11.

Where to use them

In choosing between While and Do-While I end up using the While loop 99+% of the time. Its not that I have an aversion to Do-Whiles, I just always default to a while loop and construct my logic accordingly. The only time you need to choose a Do-While over a While is if the loop always needs to run at least once, regardless of the conditional statement. Though I wouldn’t worry if you never end up using a Do-While loop.

Leave a Comment