PowerShell While


A while loop will evaluate a condition and if true will perform an action. As long as the condition evaluates to true the action will continue to be performed.


The following example creates a loop that will count down from 10 to 0

$i = 10
while($i -ge 0){

Unlike the Do-While loop the condition is evaluated prior to the action's first execution. The action will not be performed if the initial condition evaluates to false.

Note: When evaluating the condition, PowerShell will treat the existence of a return object as true. This can be used in several ways but below is an example to monitor for a process. This example will spawn a notepad process and then sleep the current shell as long as that process is running. When you manually close the notepad instance the while condition will fail and the loop will break.

Start-Process notepad.exe
while(Get-Process notepad -ErrorAction SilentlyContinue){
  Start-Sleep -Milliseconds 500