PowerShell Do While Loop [With Examples]

The Do While loop in PowerShell is useful when you need to ensure that a block of code runs at least once before checking a condition. In this tutorial, I will explain the Do While loop in PowerShell, its syntax, and practical examples of using do while loop in PowerShell.

In a “Do While” loop, PowerShell ensures that the code within the loop runs at least once, making it ideal for scenarios where the initial execution is necessary, and subsequent checks determine additional iterations.

What is a PowerShell Do While Loop?

The Do While loop in PowerShell is a control flow statement that allows you to execute a block of code repeatedly as long as a specified condition is evaluated as true. Unlike the While loop, which checks the condition before executing the code block, the Do While loop checks the condition after the code block has been executed. This ensures the code block is executed at least once, regardless of the condition.

Syntax of PowerShell Do While Loop

The basic syntax of the Do While loop in PowerShell is as follows:

Do {
    # Code block to be executed
} While (condition)

Here, the code block inside the Do statement is executed first, and then the While condition is evaluated. If the condition is true, the code block is executed again. This process repeats until the condition evaluates to false.

Read PowerShell Do-Until Loop Examples

Examples of PowerShell Do While Loop

Now, let me show you a few examples of PowerShell do while loop.

Example 1: Simple Counter

In this example, we will create a simple counter that increments a variable from 1 to 5 using the do while loop in PowerShell.

Below is the PowerShell script.

$count = 1

Do {
    Write-Output "Count: $count"
    $count++
} While ($count -le 5)

Output:

Count: 1
Count: 2
Count: 3
Count: 4
Count: 5

In this example, the loop starts with $count set to 1. The code block inside the Do statement prints the current value of $count, and then increments it by 1. The loop continues to execute as long as $count is less than or equal to 5.

I executed the above script using VS code, and you can see the output in the screenshot below:

PowerShell Do While Loop

Read While Loop in PowerShell

Example 2: User Input Validation

In this example, we will use the Do While loop to repeatedly prompt the user for input until they enter a valid number.

Here is the PowerShell script.

Do {
    $input = Read-Host "Please enter a number between 1 and 10"
} While (-not ($input -match '^[1-9]$|10$'))

Write-Output "You entered a valid number: $input"

Output:

Please enter a number between 1 and 10: 15
Please enter a number between 1 and 10: 5
You entered a valid number: 5

The loop prompts the user to enter a number between 1 and 10. The condition checks if the input matches the regular expression for a valid number in the specified range. If the input is invalid, the loop prompts the user until a valid number is entered.

Example 3: Reading File Content

In this example, we will read the content of a file line by line until we reach the end of the file.

Below is the PowerShell script that uses a do-while loop.

$filePath = "C:\MyFolder\file.txt"
$file = Get-Content $filePath -Raw
$lines = $file -split "`r`n"

$index = 0

Do {
    Write-Output $lines[$index]
    $index++
} While ($index -lt $lines.Length)

In this example, the Get-Content cmdlet reads the entire file content into a single string, and then split into an array of lines. The Do While loop iterates through the array and prints each line until the end of the array is reached.

Read How to Handle Errors with Try-Catch in PowerShell?

Do While Loop with Conditional Logic

Let us check out how to work with do while loop with conditional logic in PowerShell.

Implement Conditional Tests

Conditional tests are essential to directing the flow of a Do While loop. These tests evaluate whether the loop should continue running. Common scenarios involve checking variable values or evaluating a function’s output.

For example:

$count = 0
Do {
    Write-Output $count
    $count++
} While ($count -lt 5)

In this script, the loop runs until $count is no longer less than 5. Each iteration evaluates the condition $count -lt 5 to decide whether to proceed.

Comparison Operators

Comparison operators form the backbone of conditional logic in loops. They define the relationship between values, allowing for precise control based on these relationships.

We can also use comparison operators for the conditional logic in do while loops in PowerShell.

Here are the common operators:

  • -eq (equal)
  • -ne (not equal)
  • -gt (greater than)
  • -lt (less than)
  • -ge (greater than or equal to)
  • -le (less than or equal to).

Example:

$value = 10
Do {
    Write-Output "Value: $value"
    $value--
} While ($value -ge 0)

Here, $value -ge 0 ensures the loop runs until $value is less than zero. Each iteration checks this condition, maintaining control over the loop’s execution.

You can see the output in the screenshot below after I executed it using VS code.

do while loop in PowerShell

Read PowerShell For Loop

Handle Multiple Conditions

Now, let me show you how to handle multiple conditions in a PowerShell do while loop.

Logical operators like -and, -or, and -not combine multiple true or false values into a single condition.

Here is an example:

$x = 1
$y = 10
Do {
    Write-Output "x: $x, y: $y"
    $x++
    $y--
} While ($x -le 5 -and $y -ge 5)

In the above PowerShell script, the do-while loop continues while both $x -le 5 and $y -ge 5 are true. Logical operators ensure the loop only runs when both conditions are met.

Read Create and Use Functions in PowerShell

PowerShell do while loop with break and continue

We can use the break and continue statements to control the flow. Let me show you how to use break and continue statements within a do while loop in PowerShell.

The break statement in PowerShell completely stops a loop once a certain condition is met. For example, it can exit a do-while loop when a specific value is found in an array:

Do {
    $number = Get-Random -Minimum 1 -Maximum 100
    if ($number -eq 50) { break }
    Write-Output $number
} While ($true)

You can see the output in the screenshot below:

PowerShell do while loop with break and continue

The continue statement skips the remaining code in the current iteration and moves to the next iteration of the loop:

Do {
    $number = Get-Random -Minimum 1 -Maximum 100
    if ($number -gt 90) { continue }
    Write-Output $number
} While ($true)

I hope that now you have an idea of using break and continue statements in a do-while loop in PowerShell.

Conclusion

The Do-While loop in PowerShell helps execute code blocks repeatedly based on a specified condition. This loop evaluates the condition after the block of code runs at least once.

Here are a few benefits of using a do while loop in PowerShell.

  • Flexibility: Allows dynamic and repeated execution of tasks.
  • User Input Handling: Can manage inputs effectively.
  • Automation Strength: Enhances automation tasks by repeating actions as long as conditions are true.

I hope you know how to use the do while loop in PowerShell with the examples above. If you still have any questions, feel free to submit a comment below.

You may also like:

100 PowerShell cmdlets download free

100 POWERSHELL CMDLETS E-BOOK

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