Using Loops in PowerShell Part III

Part III of Using Loops in PowerShell. At times, we as developers will never know how many times a process is to be ran, however we may know a condition. While-loops in PowerShell a will continue looping until the condition is met. In this tutorial, you will learn how to use while-loops in PowerShell.


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

Step one.

The while loop checks to see if the condition that was specified evaluates to true, then it executes a block of code and continues to repeat until the condition specified evaluates to false.

The while-loop is written as follows:


$objRandom = New-Object Random 
$val = $objRandom.Next(1,10) 
while ($val -ne 7){ Write-Host ("You got a " + $val + "...") 
$val = $objRandom.Next(1,10) } 
Write-Host "Awesome, you've got a 7!"


Copy and Try it

When the code is ran, your output pane should appear as follows:

Step two.

The particular code generates a random number between 1 and 10 and displays the number it receives until it reaches 7. Considering that it may take a while to reach the number 7 in numerous random number generations, the while-loop allows the search to continue until the goal is reached.

The first two lines initialize a new Random object and grab the first random values. The Random object is what allows you to generate random numbers. We use the Random object’s Next method to specify the lowest and highest number you want the code to return to generate a random number.

The while-loop checks the conditions in the parenthesis to make sure the condition is met, if not, it will continue to go into the loop. In the code provided above, it checks to see whether $val is not equal to 7. If not, the code displays the value and then generates a new random number from 1 to 10. Reevaluation for the condition happens and then it continues on through the cycle until $val contains the number 7 as its value. The code stops and displays that you have 7.

Remarks last but not least

Not all instances will have a defined number of repetitious tasks, so conditional loops are there to help as much as they can. Any particular code can be in the while-loop so long as it’s a conditional code, as in True or False. Join us next time for additional Windows PowerShell tutorials