Using Loops in PowerShell Part V

Part V of Using Loops in PowerShell. In this tutorial, you will learn how to use Do-Until loops as well as learn what to avoid with loops in PowerShell.


If you have not already done so, click open Windows PowerShell ISE.

Step one.

The do until loop is similar to the do-while loop. The two are similar in the way they evaluate the condition after the first iteration of the loop. They differ in how the condition controls the loop. The do-until loop is done when the condition in the parenthesis evaluates to TRUE, while in the do-while loop, to end the loop, the condition must evaluate to FALSE.

The do-until loop is written as follows:


$objRandom = New-Object Random
                $val = $objRandom.Next(1, 10)
                Write-Host ("You got a " + $val + "...")
} while ($val –eq 7)
Write-Host "Congratulations, you got a 7!"

Copy and Try it

When the code is ran, the output pane will appear as the image presents below:

Step two.

This code technically, if you have read Part IV of Using Loops in PowerShell, exactly the same as the do-while code. The only difference is the 6th line, where $val –ne 7 has been changed to $val –eq 7. The do-until technically is the opposite of the do-while. The one thing to keep in mind so that the output is correct all the time, is the condition.

Remarks last but not least…

That is the conclusion of the loop series in PowerShell, however, there is still much to learn. Join us next time for additional Windows PowerShell tutorials! Till then…