PowerShell While Loop Explained: Syntax, Parameters, and Examples

Photo of author

By Victor Ashiedu

Published

Are you trying to add a PowerShell While Loop to your script but not sure how to proceed? This detailed guide will help you understand the While loop and learn how to use it.

Overview

PowerShell While Loop: Overview

The While loop (or statement) is a versatile PowerShell language construct. Scripters use the While statement to create a loop that runs commands in a command block.

As long as the conditional test evaluates to true in a While loop, PowerShell will continue running the commands in the block. However, the command loop will stop when the condition evaluates to false.

Another PowerShell language construct closely related to while is the For statement. However, the While loop is easier to construct than a For statement in comparison.

This is because the syntax of while is less complicated. PowerShell While Loop is easy to use because you specify a conditional test in the while statement to control how many times the loop runs.

Syntax and Parameters

Syntax And Parameters Of PowerShell While Loop

The While Loop has a simple syntax. Here it is…

 while (<condition>){<statement list>}

In the short table below, I have explained the two parameters of the while statement.

S/Nwhile Parameter NamePowerShell while Loop Parameter Meaning/Notes
1<condition>PowerShell evaluates the <condition> section of the statement before executing the <statement list> section. When PowerShell evaluates the <condition>, it resolves to either true or false. As long as the condition remains true, PowerShell re-executes the commands in the <statement list> section. When the condition in the <condition> section resolves to false, the while loop will terminate.
2<statement list>The <statement list> section of the while statement holds one or more commands that are executed each time the loop is entered or repeated. You can include any valid PowerShell statement in the <statement list> section.

Examples

So far, I have discussed a quick overview of this all-important PowerShell language construct. I have also explained the syntax of the while loop and its parameters.

With all the preambles out of the way, it is time for the good stuff. This section teaches you different ways to use the while statement in PowerShell scripting.

1. Add Timeout in While And Do Loop

The script below creates a type of timeout using PowerShell while statement.

$timestamp = New-TimeSpan -Seconds 5
$stopwatch = [System.Diagnostics.Stopwatch]::StartNew()
do {
    Write-Host "keep writing this until timeout"
} while ($stopwatch.elapsed -lt $timestamp )

This script will keep writing the information in the Write-Host command until the 5 seconds timeout.

Here is how the script achieves this..

In line 1, the command “New-TimeSpan -Seconds 5” creates a 5 seconds time stamp. Then, saves the result in the timestamp variable.

Next, in line 2 I used the System.Diagnostics.Stopwatch class to start a stopwatch. The result is saved in the stopwatch variable.

From the time you run this command, System.Diagnostics.Stopwatch class takes the current time stamp in seconds. Then, each time you execute the variable, by calling its Elapsed method ($stopwatch.elapsed), it will display the time that has elapsed from when the stopwatch started.

This takes us to the do part of the script. This is not very relevant to us – all that happens here is to execute the Write-Host command.

Finally, to the fun part, the PowerShell while loop. Here, the while loop checks the condition “$stopwatch.elapsed -lt $timestamp”.

If you remember, I said that $stopwatch.elapsed displays the time that has elapsed from when the stopwatch started. Also, note that the stopwatch started immediately after the timestamp was generated.

So, what the command, “$stopwatch.elapsed -lt $timestamp” does is check if $stopwatch.elapsed is less than $timestamp.

As far as $stopwatch.elapsed is less than $timestamp, the do loop will execute the Write-Host command, then hand over to the PowerShell while loop one more time.

This loop will continue until “$stopwatch.elapsed -lt $timestamp” returns false. That is, $stopwatch.elapsed becomes greater than $timestamp.

2. Use Break Statement with the While Loop

To demonstrate how to use PowerShell Break statement with the While Loop, I will use the script below:

$start = 1
While($start -ne 10){
   Write-Host $start
   if($start -eq 5){break}
   $start++
}

The script starts by saving the value of 1 in the start variable. Then, the PowerShell while loop checks if the value in the start variable is less than 10.

If this condition is true (that is, the value in the start variable is less than 10), the while loop executes the command in its statement part.

The command is “Write-Host $start” in this instance – writes the current value saved in the start variable.

Then comes the break clause.

This is executed in an IF statement. This statement says, “if the current value in the start variable is less than 5, break the loop” (stop the scrip from continuing the loop).

However, if the IF statement executes to false – the current value in the start variable is less than 5, the script continues to the next line of the script.

The line of the script happens to be “$start++”. The ++ operator next to the $start variable tells PowerShell to increment the value in the start variable by 1.

Once this increment is done, the PowerShell While Loop runs again. Naturally, the while loop would have continued running until the value saved in the start variable reached 10 but for the break clause.

This break clause bypasses the while loop and stops the script when the value in the start variable gets to 5. The implication of this is that the script will display 1, 2, 3, and up to 5.

How To Use PowerShell Break Statement With The While Loop

If you want to increase the number count, change 5 to your desired number. For instance, to display up to 7, I will change 5 to 7.

$start = 1
While($start -ne 10){
   Write-Host $start
   if($start -eq 7){break}
   $start++
}

3. Use While Loop with Multiple Conditions

In a While loop, adding multiple conditions is as simple as enclosing each condition in (). Then, you include the logical operator that links the conditions in between the conditions.

Here is the general syntax of a while loop with multiple conditions

while ((<condition1>) <logical operator> (<condition2>)) {<statement list>}  

The linking operator could be an -or, or -and operator in this instance.

The behavior of the while statement depends on the logical operator linking the multiple conditions. For instance, if I use the -or logical operator, the while loop will continue to run as far as one of the conditions is true.

Here is what the syntax of the command with -or looks like…

while ((<condition1>) -or (<condition2>)){<statement list>}

To demonstrate this in a real-life script, I will use the script below:

while (!(Test-Path "d:\eventlog.txt") -and !(Test-Path "D:\flag.txt")) 

{ Start-Sleep 10 }

The script tests if the files eventlog.txt and flag.txt exist in the specified path. If the files DO NOT exist, the script will continue delaying the script for 10 seconds.

So, every 10 seconds, the while loop will check the conditions again (do the files exist?). If the files still do not exist, the while loop will run the start-sleep again and continue delaying the script for 10 seconds.

If you’re wondering how you can apply this in a script, here is how. Say you’re writing a script that depends on two files to continue. Also, assuming that these two files are generated by another process and without the files, your script will fail.

Or, better still, there is no need for the remaining part of your script to run unless these two files exist.

Then, you can use the above while statement to continue delaying the script until the process that creates the files creates them.

4. Create an Infinite While Loop that Always Returns True

If you wish to create an infinite PowerShell While Loop, use the $true constant variable in the condition part of the while loop.

Here is the syntax…

while ($true){
Start-Sleep -Seconds 1  
}

This while loop will run infinitely until you press Ctrl + C keys on your keyboard simultaneously; here is why.

The while loop will check the condition in the condition part of the loop. In this instance, it will always return true since we have the $true constant variable there.

Then, the while loop will execute the command in the part of the loop that contains the PowerShell statements to run. In this script, it is “Start-Sleep -Seconds 1 “.

That commands delays for 1 second, and the loop starts again. When I ran this script in PowerShell ISE, it ran continuously until I manually stopped it.

5. Create an Incremental Variable in a While and Do Loop

To demonstrate how to use Powershell While and Do loop to create an incremental variable, I’ll use the script below:

$initvalue = 1;
do {
    Write-Host $initvalue;
    $initvalue++;
}
while ($initvalue -le 10)
Write-Host "Finished";

In the first line of the code, I saved the value of 1 in the initvalue variable. Then, in the do loop, I use Write-Host to display the value in the initvalue variable.

At first, this value is 1.

Then, in the second line of code within the do loop, I increment the value of the initvalue variable by 1.

I achieved this by adding the ++ operator next to the variable. At this point, the value of the value has increased from 1 to 2.

Next, I use the while loop to add a condition that checks if the value of the initvalue variable is less than or equal to 10. As far as this condition remains true, the whole script will keep running until the value reaches 10.

At the point initvalue variable is 10, the script will display “Finished”. Here is the result of this script in PowerShell ISE.

In this example, the most important bit to note is the use of the ++ operator to increment the value in the initvalue variable

6. Create a Number Counter with While Loop

You can use PowerShell While loop to count numbers up or down. For example, you can create a script that counts from 10 to 0.

Alternatively, you can create a script that counts from 0 to 10. Here are the scripts that count down from 10 to 0 and count up from 0 to 10.

#count from 10 to 0
$startcount = 10; 
while ($startcount -ge 0) 
{ write-output $startcount; 
$startcount--; }

#count from 0 to 10
$endcount = 0; 
while ($endcount -le 10) 
{ write-output $endcount; 
$endcount++; }

And here are the results in PowerShell ISE.

How To Create A Number Counter With PowerShell While Loop

Now, let’s see how the scripts work. Here is the count-down script…

#count from 10 to 0
$startcount = 10; 
while ($startcount -ge 0) 
{ write-output $startcount; 
$startcount--; }

The first line is a comment – just for information only. The actual script starts in line 2.

In line 2, I defined the number the count-down counter starts from. In this instance I want the counter to count down from 10.

Then, in line 3, I used the PowerShell While Loop to check the condition “$startcount -ge 0”. Every time the while loop checks this condition and it returns true, the while loop will proceed to the next step.

In the next line, the script writes the current value of the startcount variable. Finally, PowerShell will decrement the startcount variable by 1.

The decrement action is performed by the — operator next to the $startcount variable. The while loop will continue until the condition “$startcount -ge 0” returns false.

When the while condition returns false (the startcount variable is less than or equal to 0 (zero)), the PowerShell while loop will terminate.

Moving on to the count-up counter (script shown below), the reverse explanation is true.

#count from 0 to 10
$endcount = 0; 
while ($endcount -le 10) 
{ write-output $endcount; 
$endcount++; }

7. Limit While Loop by Time

Do you want to limit how long a PowerShell while loop runs before it terminates? To achieve this define a time limit that determines how long you want the while loop to run.

Then, check if how long the while loop has been running exceeds the time limit. In essence, you’ll be adding multiple conditions in the while loop, linked by an -or operator.

One of the conditions checks the state of the command you’re running. Then, the second condition checks whether the current time (using Get-Date), is less than or equal to the initial time limit you define.

OK. Enough of talks, let’s script!

In this example, I want to check whether the status of a service called WinRM equals running. Here is the command that checks the status of this service.

(Get-Service -Name WinRM).Status -eq "Running"

Meanwhile, to use the while loop to terminate the script after a pre-defined time, I’ll use this script.

$timelimit = (Get-Date).AddSeconds(30)
while ((Get-Service -Name WinRM).Status -eq "Running" -or (Get-Date) -le $timelimit ) {
  Start-Sleep -Seconds 1
}

In the first line of the script, I used the AddSeconds method of the Get-Date cmdlet to define the time limit – I saved this information in the timelimit variable.

Then, in the second line of the code, I introduced the while loop. This is where the magic happens!

Here is the condition portion of the PowerShell while Loop:

while ((Get-Service -Name WinRM).Status -eq "Running" -or (Get-Date) -le $timelimit ) 
In this example, I want the while loop to terminate after 30 seconds no matter the status of the service.

As I explained earlier, the condition portion of the while Loop combines the command that checks the status of the WinRM service…

(Get-Service -Name WinRM).Status -eq "Running"

If this was the only condition in the while statement, the loop will run until the status of the service changes to Running. At that point, the condition in the while loop will be true.

But, I want to limit how long the while loop runs even if the state of the WinRM service has not changed to Running.

To achieve this, I introduced a second condition into the while loop…

-or (Get-Date) -le $timelimit 

This condition checks if the current time is less than or equal to the initial time I set and saved in the timelimit variable (30 seconds). When the current time is less than or equal to 30 seconds from when I started running the script, the second condition will change from true to false.

At this point, it doesn’t matter whether the status of the WinRM service has not changed to Running or not; the script will terminate.

So, to finally see how this script scripts, when I run it, it stays running for 30 seconds and terminates.

The state of the WinRM service is generally always Stopped, except when it’s required. In the screenshot below, when the highlighted button is on, it indicates that PowerShell ISE is running a script.

30 seconds, the button turns gray, indicating that the script has stopped running.

How To Limit PowerShell While Loop By Time

Frequently Asked Questions

1. How do you run a While loop in PowerShell?

The general syntax of a PowerShell While Loop is:

while (){}

So, to run a While loop, add at least one condition to the condition’s part of the While loop. Then, add the commands you wish to run in the statement list portion.

2. How do you use the and operator in PowerShell?

The and operator is one of the three logical operators. Logical operators connect statements in PowerShell.

So, when you connect two PowerShell statements with the and operator, the statement will evaluate to TRUE when both conditions are TRUE.

For example.

The command “(1 -eq 1) -and (1 -lt 2)” will evaluate to TRUE since both conditions equal TRUE.

3. How do I pause a PowerShell script?

If you wish to manually restart your script by pressing the Enter key, use the pause command. When you type pause and press enter, PowerShell will display…

Press Enter to continue…:

When you press Enter, PowerShell will unpause.

Alternatively, if you want to pause a PowerShell script for a specified time, use the Start-Sleep command.

4. How do you break a loop in PowerShell?

To break a loop in PowerShell, use the break clause. Anytime PowerShell sees the break clause, it terminates the current operation.

5. What is $null in PowerShell?

$null is an automatic variable in PowerShell. It is used to represent NULL. In PowerShell, NULL is NOT zero, it is NULL.

Conclusion

The PowerShell While Loop is so important that every serious PowerShell enthusiast should know how to use it.

To summarize this guide, the while loop has two important elements: the condition and the statement list.

The condition part of the loop is where you add condition(s) that the while loop evaluates to determine whether to continue or terminate. On the other hand, you add PowerShell commands (statements) to the statement list section.

My aim in writing this guide was to help you understand how the PowerShell While loop works and how to use it. I hope I was able to help you achieve this aim.

If you did, click on “Yes” beside the “Was this page helpful” question below. You may also express your thoughts and opinions by using the “Leave a Comment” form at the bottom of this page.

Finally, I deeply feel that you’ll find our other Windows PowerShell Explained articles useful as well. We also have Windows PowerShell How-To Guides, that offer you more ways to learn PowerShell.

We go the extra mile to deliver the highest quality content for our readers. Read our Content Writing, Content Review, and Anti-Plagiarism policies to learn more.

About the Author

Photo of author

Victor Ashiedu

Victor is the founder of InfoPress Media, publishers of Ilifeguides and Itechguides. With 20+ years of experience in IT infrastructure, his expertise spans Windows, Linux, and DevOps. Explore his contributions on Itechguides.com for insightful how-to guides and product reviews.

Related Articles

Get in Touch

If this article does not meet your expectations, kindly let us know. We have various ways you can get in touch with us:

  1. Respond to "Was this page helpful?" above
  2. Leave a comment with the "Leave a Comment" form below
  3. Email us at [email protected] or via the Contact Us page.

Leave a comment