fbpx

How To Use PowerShell While Loop? 4 Best Examples

A robust scripting language, PowerShell offers a wide range of tools for automating and managing Windows-based systems. The PowerShell while loop is among the most often employed building blocks.

How To Use PowerShell While Loop? 4 Best Examples

The PowerShell while loop is an iterative loop that continues until the condition is met. The while block allows you to write numerous lines of code and run them repeatedly until the required conditions are met. It is similar to a FOR loop, but it has a distinct structure.

1. PowerShell while loop Winth Syntax

The single condition kind of while loop is among its most basic variations. In contrast to the If statement, this kind of loop only acts when a specific condition evaluates to true. The loop ends when a value of ‘False’ is returned, and the remainder of the script is then executed.

  • The usage of parenthesis will be the first thing you notice. The code block is a collection of PowerShell commands that run when the condition is true, and the condition must be wrapped in parentheses.
  • The second item to be aware of is the requirement that the condition produces a Boolean value that can only be either True or False.
while (condition)

{

# Code block you need to execute

}

Create a loop code below, where $val is initialized to 0 and has its value increased by 1 each time the code loop executes until it reaches 8.

The loop ends and the remainder of the script is executed when $val reaches a value of 8, making the condition False.

# Set the initial value of the $val variable to 0
$val = 0

# Causes the while loop to continue running until the value of the $val variable reaches 8.


while($val -ne 8)
{
$val++
Write-Host $val
}

while($val -ne 8)
{
$val++
Write-Host $val
}

2. Running a while loop in PowerShell with built-in variables ($true/$false)

Using conditions within a while loop is effective. However, you can easily make a While loop using built-in PowerShell variables like $true and $false. The following syntax runs until $true no longer exists.

In other words, the cycle never ends. However, you must always provide a method to exit an endless cycle. If not, you are helplessly trapped. 

Run the code block below, which prints the value of $i to the console and runs indefinitely.

# 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

}
Running a while loop in PowerShell with built-in variables

Press Ctrl+C to exit the loop at this time. Be cautious when using system resources because this loop uses a lot of them.

3. How To Execute Multi-Condition While Loops?

You can make multi-condition while loops in addition to single-condition while loops. like the singular circumstance The conditions in a while loop must provide a Boolean value, either True or False.

Similar to the syntax for a single-condition while loop, the syntax for a multi-condition while loop is shown below. The primary distinction is that the following operators can be used to separate several conditions:

Both requirements must be true, AND (-and).
OR (-or) (Either of the two possibilities is true).

Syntax

# AND operator

while (condition1 -AND condition2)

{

# Code block to execute
}

# OR operator

while (condition1 -OR condition2)
{

# Code block to execute

}

Run the code below, which loops while $val and $i are not equal to 3 and 5, respectively.

The loop terminates and the remainder of the script’s execution resumes after both variables’ values have met their corresponding conditions.

$val and $i are declared with initial values of 0

$val = 0
$i = 0

# Tells the While loop to continue running until $val and $i are both equal to 3 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"
}

4. Using the keywords BREAK and CONTINUE in While Loops

You’ve seen how While loops provide your PowerShell script more adaptability. But add the break and continue keywords to better manage the execution of your while loops.

Use the BREAK keyword to end the loop once the specified number of elements in an array have been handled if you only want to process a specific number of them.

KeywordFunction
Continue Skips the final code block of the current loop iteration and moves on to the following iteration.
Break Immediately ends the loop and resumes script execution from there.

Run the code below to iterate through a 10-item array in a loop.

The value of $i is verified by the if statement. The continue keyword skips the remaining code in the loop and moves on to the following iteration if $i equals 5. The break keyword ends the loop if $i is equal to 8.

If not, the while loop writes (Write-Host) and raises the value of the $i variable by 1.

# 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++
}

The fifth and eighth entries in the array were skipped by the loop. After processing the seventh and eighth elements in the array, the while loop ended.