Part IV of Using Loops in PowerShell. Another variation of the while loop, is the do-while loop. In this tutorial, you will learn how to use Do-While loops in PowerShell.
If you have not already done so, click open Windows PowerShell ISE.
You can run the same loop functions with a do-while like you do a while-loop. The difference between the two is that do-while loops evaluate the condition AFTER the code in the loop block has been executed. The only guarantee is that your code will run at least once.
The do-while loop is implemented as follows:
Example
$objRandom = New-Object Random
do {
$val = $objRandom.Next(1, 10)
Write-Host ("You got a " + $val + "…")
} while ($val –ne 7)
Write-Host "Congratulations, you got a 7!"
The following image shows the result in the output pane of the do-while being ran.
If you have taken a peek or have done the Part III of Using Loops in PowerShell, the While-loop actually gives you the Congratulations message before the, "You got a 7" output.
Do-whiles are useful but not quite used as much as the other loops we demonstrate on the site. Join us next time for additional Windows PowerShell tutorials