---
title: "The PowerShell While Loop : A Back to Basic Guide"
description: "Discover the many ways to utilize the PowerShell while loop and take control of your applications flow with this ATA Learning tutorial!"
canonical: "https://adamtheautomator.com/powershell-while-loop/"
---

# The PowerShell While Loop : A Back to Basic Guide

> Discover the many ways to utilize the PowerShell while loop and take control of your applications flow with this ATA Learning tutorial!

Source: https://adamtheautomator.com/powershell-while-loop/

---

ATA Learning

Tap to hide

[

ATA Learning

](/)

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Search for:  

*   [](https://twitter.com/adbertram)
*   [](https://github.com/Adam-the-Automator)
*   [](https://www.linkedin.com/company/adam-the-automator-llc)
*   [](/feed/)

![The PowerShell While Loop : A Back to Basic Guide](https://adamtheautomator.com/wp-content/uploads/2022/11/The-PowerShell-While-Loop-A-Back-to-Basic-Guide.jpg)

# The PowerShell While Loop : A Back to Basic Guide

[![](https://secure.gravatar.com/avatar/2788bb1a3f735603f81eca51d68daec56a9d97e805a10268fb2c20afcc76b81b?s=192&d=mm&r=g)Nicholas Xuan Nguyen](https://adamtheautomator.com/author/nicholas-xuan-nguyen/)23 November 20226 min. read

Categories: [IT Ops](/category/it-ops/)

Tags:[PowerShell](/tag/powershell/)[PowerShell Language](/tag/powershell-language/)

Table of Contents

*   [Prerequisites](#prerequisites)
*   [Executing Single Condition while Loops](#executing-single-condition-while-loops)
*   [Executing PowerShell While Loop with Built-in Variables ($true/$false)](#executing-powershell-while-loop-with-built-in-variables-truefalse)
*   [Executing Multi-Condition While Loops](#executing-multi-condition-while-loops)
*   [Using BREAK and CONTINUE Keywords in While Loops](#using-break-and-continue-keywords-in-while-loops)
*   [Limiting the Time a While Loop Runs](#limiting-the-time-a-while-loop-runs)
*   [Conclusion](#conclusion)

PowerShell is a powerful scripting language that provides many features for automation and managing Windows-based systems. One of the most commonly used constructs is the PowerShell `while` loop.

Worry not if you have been stuck in an endless loop while trying to learn PowerShell scripting. Let the PowerShell `while` loop guide you to your great escape. And in this tutorial, you will jump back to the basics of working with `while` loops in PowerShell as you write your scripts.

Read on to take your PowerShell scripting skills to the next level!

## Prerequisites

This tutorial will be a hands-on demonstration. To follow along, be sure you have the following:

Related:[PowerShell 7 Upgrade: A How to Walk Through](https://adamtheautomator.com/powershell-7-upgrade/)

*   A Windows machine – This tutorial uses Windows 10.
*   Windows PowerShell 5.0 or higher installed – This tutorial uses PowerShell 7.
*   A user account with [administrator privileges](https://support.microsoft.com/en-us/windows/create-a-local-user-or-administrator-account-in-windows-20de74e0-ac7f-3502-a866-32915af2a34d).

## Executing Single Condition `while` Loops

One of the simplest types of `while` loop is the single condition type. Unlike the [`If`](https://adamtheautomator.com/powershell-if-statement/) statement, this type of loop executes a set of given commands so long as a specified condition evaluates to true. When a ‘False’ is returned, the loop breaks, and the execution continues with the rest of the script.

Related:[Back to Basics: Conditional Logic with PowerShell If-Else](https://adamtheautomator.com/powershell-if-statement/)

Below is the syntax for a single condition `while` loop:

*   The first thing you will notice is the use of parentheses. The condition must be enclosed in parentheses, while the code block is a set of PowerShell commands that executes while the condition is true.
*   The second thing to note is that the condition must return a Boolean value, which evaluates to either True or False.

```powershell
while (condition)
{

	# Code block to execute

}
```

Run the code below, where the value of `$val` starts at `0` and is incremented by `1` each time the code block runs until the `$val` variable’s value equals `3`.

When `$val` reaches a value of `3`, which makes the condition False, the loop breaks, and execution continues with the rest of the script.

```powershell
# Declares the $val variable with the initial value of 0
$val = 0

# Sets the while loop to run until the $val variable's value reaches 3
while($val -ne 3)
{
	# Increments the $val variable's value by 1
	$val++
	
	# Prints the current value of the $val variable
	Write-Host $val
}
```

![Understanding Single Condition While Loops.](https://adamtheautomator.com/wp-content/uploads/2022/11/image-320.png)

Understanding Single Condition While Loops.

Related:[Understanding the PowerShell Write-Hostt Cmdlet](https://adamtheautomator.com/powershell-write-host/)

## Executing PowerShell While Loop with Built-in Variables (`$true`/`$false`)

The previous example, using conditions in the `while` loop, works fine. But you can also use PowerShell’s built-in variables, such as `$true` and `$false`, to create a `While` loop.

The syntax below executes until `$true` is no longer `$true`. In other words, the loop runs forever. But you must always include a way to break out of an infinite loop. Otherwise, you are forever stuck. You will learn more about how to break from a loop using `break` and `continue` later in this tutorial.

```powershell
while($true)
{

	# Code block to execute

}
```

Execute the code block below, which runs forever, printing the value of `$i` to the console.

```powershell
# Declares the $i variable with the initial value of 0
$i = 0

# Sets the While loop to run while the condition is $true
while($true)
{
	# Increments the $i value by 1
	$i++
	
	# Prints the $i variable's current value
	Write-Host $i
}
```

Now, press Ctrl+C to break out of the loop. This loop consumes many system resources, so be careful when using them.

![Executing a while loop with PowerShell’s built-in ($true) variable](https://adamtheautomator.com/wp-content/uploads/2022/11/image-321.png)

Executing a `while` loop with PowerShell’s built-in (`$true`) variable

## Executing Multi-Condition `While` Loops

In addition to single-condition `while` loops, you can also create multi-condition while loops. Like the single condition `While` loop, the conditions must return a Boolean value, either True or False.

Below is the syntax for a multi-condition `while` loop, similar to the syntax for a single-condition `while` loop. The main difference is that you can include multiple conditions separated by the following operators:

*   AND (`-and`)- Both conditions must be true.
*   OR (`-or`) (Either condition can be true).

```powershell
# AND operator
while (condition1 -AND condition2)
{

	# Code block to execute

}

# OR operator
while (condition1 -OR condition2)
{

	# Code block to execute

}
```

Execute the code below, which loops `while` `$val` is not equal (`-ne`) to `3` `-and` `$i` is not equal (`-ne`) to `5`.

When both variables’ values reach their respective conditions, the loop breaks, and execution continues with the rest of the script.

```powershell
# Declares the $val and $i variables with initial values of 0
$val = 0
$i = 0

# Sets the While loop to execute until $val is equal to 3 and $i is equal to 5
while($val -ne 3 -and $i -ne 6)
{
	# Increments $val by 1
  $val++
	# Increments $i by 2
  $i += 2
	# Prints $val and $i variables' current value
  Write-Host "$val, $i"
}
```

Related:[Learning the PowerShell Not Equal Operator with Examples](https://adamtheautomator.com/powershell-not-equal/)

![Executing a  loop with AND operator](https://s3-us-west-2.amazonaws.com/secure.notion-static.com/26a3f399-301f-4a25-b08a-8a494aa4b5fa/Untitled.png)

Executing a `while` loop with AND operator

![Executing a while loop with AND operator](https://adamtheautomator.com/wp-content/uploads/2022/11/image-322.png)

Executing a `while` loop with AND operator

Now, execute the below code, which asks the user for their age, stored in the `$age` variable.

If the user enters a number either less than (`-lt`) `1` or is not a number (`-nomatch`), the user is prompted again to enter a valid number. This behavior is useful in giving users multiple chances to enter valid input.

```powershell
# Prompts the users to enter their age
$age = Read-Host "Please Enter Your Age"

# Sets the While loop to run until the user provides a valid input
while($age -notmatch "\\d+" -or $age -lt 1)
{
	# Re-prompts the user to enter a valid age number
  $age = Read-Host "Please Enter Your Valid Age"
}
# Prints the valid age input
Write-Host "Your age is $age
```

In the output below, you can see the user was prompted to enter their age three times, as follows:

*   The first time, the user entered **ten**, which is not a number.
*   The second time, the user entered **0**, which is below 1.
*   The third time, the user entered **10**, which is a valid age.

![Executing a while loop with the OR operator](https://adamtheautomator.com/wp-content/uploads/2022/11/image-323.png)

Executing a `while` loop with the OR operator

## Using BREAK and CONTINUE Keywords in While Loops

You have seen how `while` loops add flexibility to your PowerShell script. But to better control, your While loops’ execution, add the `break` and `continue` keywords.

For example, if you only want to process a certain number of items in an array, you can use the BREAK keyword to exit the loop when the desired number of items has been processed.

These keywords function as follows:

| Keyword | Function |
| --- | --- |
| break | Immediately exits the loop and continues execution with the rest of the script. |
| continue | Skips over the remaining code block in the current iteration of the loop and continues with the next iteration. |

Execute the code below, which loops through an array of 10 items.

In the code below, the `if` statement checks the value of `$i`. If the value of `$i` is `5`, the `continue` keyword skips over the remaining code in the loop and continues with the next iteration. If the value of `$i` is `8`, the `break` keyword exits the loop and continues with the rest of the script.

Otherwise, the `while` loop prints (`Write-Host`) and increments the `$i` variable’s value by `1`.

Related:[Build Better Scripts with PowerShell ArrayLists and Arrays](https://adamtheautomator.com/powershell-array/)

```powershell
# Declares an $array of 10 items
$array = 1..10
# Declares the $i variable with the initial value of 0
$i = 0
# Sets the While look to execute until the condition is met
while($i -lt $array.Count)
{
	# Checks if $i equals 5
  if($i -eq 5)
  {
		# If yes, increment $i by 1
    $i++
		# Continue with the next iteration
    continue
  }
	# Checks if $i equals 8
  if($i -eq 8)
  {
		# If yes, break the While loop and continue with the rest of the script
    break
  }
	# Prints the current value of $i
  Write-Host "Processing item $i"
	# Increments $1 by 1
  $i++
}
```

As you can see in the output below, the loop skipped over the fifth and eighth items in the array. The `while` loop processed all other items in the array and exited after reaching the eighth item.

![Executing a while loop with break and continue keywords](https://adamtheautomator.com/wp-content/uploads/2022/11/image-324.png)

Executing a `while` loop with `break` and `continue` keywords

## Limiting the Time a While Loop Runs

Typically, you may want to limit the amount of time a loop runs. Perhaps you are trying to connect to a remote server. If so, you can give the server time to respond before timing out and exiting the loop by using the [`Start-Sleep`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/start-sleep?view=powershell-7.2) cmdlet inside your `while` loop.

The `Start-Sleep` cmdlet pauses the execution of the script for a specified amount of time.

Related:[Start-Sleep: The Simple yet Underrated PowerShell Cmdlet](https://adamtheautomator.com/start-sleep/)

Execute the code below to get and store the current date and time [`Get-Date`](https://learn.microsoft.com/en-us/powershell/module/microsoft.powershell.utility/get-date?view=powershell-7.2) in the `$startTime` variable. The `while` loop runs while the current date/time is less than `10` seconds from the value stored in `$startTime`.

As the `while` loop runs, a message prints while the `Start-Sleep` cmdlet pauses the execution of the script for `1` second.

> _The code block below is just a boilerplate for what you would actually use in practice. You can put more in the code inside the loop as needed._

Related:[The Practical PowerShell Get-Date to Demystify Date and Time](https://adamtheautomator.com/powershell-get-date/)

```powershell
# Get and store the current date/time
$startTime = Get-Date
# Sets the While loop to run while the current date/time is less than 10 seconds 
	# from the value stored in $startTime.
while((Get-Date) -lt ($startTime.AddSeconds(10)))
{
	# Prints a message
  Write-Host "Waiting for server to respond..."
	# Pauses the script for one second
  Start-Sleep -Seconds 1
}
```

Below, you can see the loop continued to run for 10 seconds before exiting the loop.

![Limiting the time a while loop runs](https://adamtheautomator.com/wp-content/uploads/2022/11/image-325.png)

Limiting the time a `while` loop runs

## Conclusion

PowerShell `while` loops come in handy when faced with complex concepts to avoid getting stuck in a loop or as you write your scripts. And in this tutorial, you have learned many ways to work with `while` loops for more flexible and powerful scripts.

With this newfound knowledge, the sky is the limit. So why not maximize the use of logical operators and keywords to automate tasks with your scripts?

Related:[PowerShell Scheduled Task : Amazing Way to Manage Tasks](https://adamtheautomator.com/powershell-scheduled-task/)

Share this article

[Share on X](https://twitter.com/intent/tweet?url=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-while-loop%2F&text=The%20PowerShell%20While%20Loop%20%3A%20A%20Back%20to%20Basic%20Guide)[Share on Facebook](https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-while-loop%2F)[Share on LinkedIn](https://www.linkedin.com/sharing/share-offsite/?url=https%3A%2F%2Fadamtheautomator.com%2Fpowershell-while-loop%2F)

## Related Posts

![](https://adamtheautomator.com/wp-content/uploads/2023/08/powershell-approved-verbs.jpg)

### [Your Getting Started Guide to PowerShell Approved Verbs](/powershell-approved-verbs/)

Discover how to get started with PowerShell Approved Verbs to make sure your scripts and code is top-notch in this ATA Learning tutorial!

![](https://adamtheautomator.com/wp-content/uploads/2023/07/powershell-sort-object.jpg)

### [Learning PowerShell Sort-Object with Examples](/powershell-sort-object/)

Learn all of the ins-and-outs of the PowerShell Sort-Object cmdlet in this example driven tutorial by ATA Learning!

![](https://adamtheautomator.com/wp-content/uploads/2023/03/powershell-change-directory.jpg)

### [PowerShell Change Directory: Navigating Your File System](/powershell-change-directory/)

Learn how to use the PowerShell change directory command to navigate your file system with ease. Master the basics of PowerShell file navigation today.

## Categories

*   [IT Ops](/category/it-ops/)
*   [Cloud](/category/cloud/)
*   [DevOps](/category/devops/)
*   [Home Ops](/category/home-ops/)
*   [Information Security](/category/infosec/)
*   [Software Development](/category/software-development/)

## Site

*   [Home](/)
*   [Tutorials](/tutorials/)
*   [Instructors](/author/)
*   [Advertising](/advertising/)
*   [Recommended Resources](/resources/)
*   [About Adam](/about-adam/)

Copyright 2026© ATA Learning | [Privacy Policy](/privacy/)
