While Loop in PowerShell [With Examples]

You should know about looping if you want to iterate through items until a condition is met in PowerShell. I will show you how to use the while loop in PowerShell in this tutorial with a few examples.

What is a While Loop in PowerShell?

A while loop is a control flow statement that enables you to execute a block of code repeatedly as long as a specified condition evaluates to true. It’s particularly useful when you need to perform repetitive tasks or iterate through items until a certain condition is met.

The while loop checks the condition before executing the block of code. If the condition is true, the code block runs; if the condition is false, the loop terminates, and the script continues executing the subsequent commands.

Syntax of the PowerShell While Loop

The syntax of a while loop in PowerShell is like the below:

while (condition) {
    # Code block to execute
}
  • condition: This is the expression that is evaluated before each iteration. If it returns true, the loop continues; if it returns false, the loop stops.
  • # Code block to execute: This is the block of code that runs repeatedly as long as the condition is true.

Now, with a few examples, let us see how to work with the while loop in PowerShell.

Read PowerShell Do While Loop

PowerShell While Loop Examples

Let us see a few examples of a while loop in PowerShell.

Example 1: Basic While Loop Example

To understand the PowerShell while loop, let us first take a simple example of printing numbers from 1 to 5. Below is the PowerShell script.

$i = 1
while ($i -le 5) {
    Write-Output $i
    $i++
}

In this example:

  • We initialize a variable $i with the value 1.
  • The condition $i -le 5 checks if $i is less than or equal to 5.
  • Inside the loop, we print the value of $i and then increment it by 1 using the ++ operator.

You can see the output in the screenshot below after I executed the above PowerShell script using VS code.

powershell while loop

Example 2: While Loop with Array Example

Here is an example of how to use the PowerShell while loop to iterate through an array of strings and print each element.

$fruits = @('Apple', 'Banana', 'Cherry', 'Date', 'Elderberry')
$i = 0
while ($i -lt $fruits.Length) {
    Write-Output $fruits[$i]
    $i++
}

Here:

  • We define an array $fruits containing a list of fruit names.
  • The condition $i -lt $fruits.Length ensures that the loop runs as long as $i is less than the length of the array.
  • We print each fruit name and increment $i by 1.

I also executed the above script, and you can see the exact required output in the screenshot below:

PowerShell While Loop Examples

Example-3: While Loop With Variables and Operators

In this example, let me show you how to use variables and operators in a PowerShell while loop.

We can use PowerShell Variables, which hold values that change with each iteration, to effectively control the loop’s flow.

Here is an example:

$counter = 0
$maxLimit = 20
while ($counter -lt $maxLimit) {
    if ($counter % 3 -eq 0) {
        Write-Output "Counter $counter is divisible by 3"
    }
    $counter++
}

This loop uses the $maxLimit variable to determine how many times the loop will iterate. It checks if $counter is divisible by 3 before printing a message.

In the same way, we can use logical operators like -and, -or, and -not to make conditions more flexible.

Here is the complete PowerShell script:

$isRunning = $true
$counter = 0
while ($isRunning -and $counter -lt 10) {
    Write-Output "Counter is $counter"
    $counter++
    if ($counter -eq 5) {
        $isRunning = $false
    }
}

In this example, the loop stops early when $counter reaches 5 because $isRunning is set to false.

Read PowerShell Do-Until Loop Examples

How to Use Break and Continue in While Loop

Let me show you now how to use the break and continue keywords to control how the for loops execute in PowerShell.

Break Statement

The break statement is used to exit the loop prematurely, regardless of the condition. It can be useful when you need to terminate the loop based on a specific condition inside the loop.

Here is an example of how to use the break in a for loop in PowerShell.

$i = 1
while ($i -le 10) {
    if ($i -eq 5) {
        break
    }
    Write-Output $i
    $i++
}

In this example:

  • The loop starts with $i initialized to 1 and runs while $i is less than or equal to 10.
  • When $i equals 5, the break statement is executed, terminating the loop.
  • As a result, the loop prints numbers 1 to 4 and then stops.

The screenshot below shows the exact output after I executed the above script.

powershell while loop break

Continue Statement

The continue statement skips the remaining code in the current iteration and moves to the next iteration of the loop. It’s useful to skip certain iterations based on a condition.

Here is an example of how to use the continue statement in a for loop in PowerShell.

$i = 1
while ($i -le 10) {
    $i++
    if ($i % 2 -ne 0) {
        continue
    }
    Write-Output $i
}

In this example:

  • The loop runs while $i is less than or equal to 10.
  • We increment $i at the beginning of each iteration.
  • If $i is an odd number ($i % 2 -ne 0), the continue statement skips the rest of the code in the current iteration.
  • As a result, only even numbers are printed.

You can also look at the screenshot below for the output:

powershell while loop continue

Read Create and Use Functions in PowerShell

How to Use Multiple Conditions in While Loop in PowerShell

In a PowerShell while loop, we can also use multiple conditions. Let me show you how.

In PowerShell, you can use multiple conditions in a while loop by combining them with logical operators such as -and, and -or. The while loop will continue to execute as long as the combined condition is evaluated as true.

Syntax

The basic syntax for a while loop with multiple conditions is:

while (<condition1> -and <condition2> -and <condition3>) {
    # Code to execute as long as all conditions are true
}

or

while (<condition1> -or <condition2> -or <condition3>) {
    # Code to execute as long as at least one condition is true
}

Example

Here’s an example that explains a while loop with multiple conditions using the -and operator. This loop will continue to run as long as both conditions are true:

$counter = 0
$limit = 10
$continue = $true

while ($counter -lt $limit -and $continue) {
    Write-Output "Counter is $counter"
    $counter++

    # Simulate a condition to exit the loop
    if ($counter -eq 5) {
        $continue = $false
    }
}

In this example:

  • The loop will continue as long as $counter is less than $limit and $continue is $true.
  • Inside the loop, the Write-Output cmdlet prints the current value of $counter.
  • The $counter variable is incremented by 1 in each iteration.
  • When $counter reaches 5, $continue is set to $false, causing the loop to exit after the current iteration.

Here is the output you can see in the screenshot below:

powershell while loop multiple conditions

Read How to Use Multiple Conditions in PowerShell If Else Statement?

Nested While Loop in PowerShell

This is very useful; you should know how to work with nested while loops in PowerShell.

Nested while loops in PowerShell are used when you need to perform iterative operations within another set of iterative operations.

Nested While Loop Syntax

The basic syntax for nested while loop is:

while (<outer condition>) {
    while (<inner condition>) {
        # Code to execute in the inner loop
    }
    # Code to execute in the outer loop
}

Nested While Loop Example

Here’s an example that shows nested while loops by generating a simple grid of coordinates:

# Initialize outer loop variables
$x = 0
$xLimit = 3

# Outer while loop
while ($x -lt $xLimit) {
    # Initialize inner loop variables
    $y = 0
    $yLimit = 3

    # Inner while loop
    while ($y -lt $yLimit) {
        # Display the current coordinates
        Write-Output "Coordinates: ($x, $y)"
        # Increment the inner loop variable
        $y++
    }
    # Increment the outer loop variable
    $x++
}

In this example:

  • The outer while loop iterates over the x coordinate.
  • The inner while loop iterates over the y coordinate.
  • For each iteration of the inner loop, the current coordinates (x, y) are displayed using Write-Output.
  • The inner loop variable $y is incremented in each iteration of the inner loop.
  • After the inner loop completes, the outer loop variable $x is incremented, and the process repeats until the outer condition is no longer true.

If you execute the above code using VS code, you can see the output in the screenshot below:

Nested While Loop Example PowerShell

Conclusion

I hope you got an idea of how to work with while loop in PowerShell with various examples.

I have also explained how to use break and continue in a PowerShell while loop and how to use multiple conditions in a while loop in PowerShell. I explained how to work with nested for loop in PowerShell at the end using an example.

If you still have any questions, feel free to let us know in the comment box below.

You may also like the following tutorials:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

FREE Download an eBook that contains 100 PowerShell cmdlets with complete script and examples.