PowerShell: How to use Do-While, Do-Until Loops?

As a PowerShell user, you may be familiar with the concept of loops. They are an essential component of scripting and automation tasks in PowerShell. The Do-While and Do-Until loops are used when you want to perform an action at least once and then repeat it based on a certain condition. In this article, we’re going to cover everything there is to know about PowerShell “Do while” and “Do until” loops, including what they are, how they work, and how they can be used. We will also provide examples of how it can be used to make your PowerShell scripts more efficient. So, let’s get started!

Introduction to PowerShell Do-While and Do-Until Loops

A loop in PowerShell is a block of code that is executed repeatedly, as long as/until a certain condition is met. It’s a powerful tool that can be used to automate processes and tasks, making them much more efficient. These loops are used in many different programming languages, including PowerShell. PowerShell supports several types of loops, including ‘For’, ‘ForEach’, ‘While’, ‘Do While’, and ‘Do Until’.

The Do While and Do Until loops are two of the most commonly used while loops in PowerShell. The Do While loop is used when you want to execute a set of instructions until a certain condition is met, while the Do Until loop is used when you want to execute a set of instructions until a certain condition is false.

To create a Do While or Do Until loop in PowerShell, you need to use the keywords ‘Do’ and ‘While’ or ‘Do’ and ‘Until’. You then need to specify the instructions to be executed and the condition. For example, to execute a set of instructions until a certain value is reached, you could use the following syntax:

Understanding the ‘Do While’ Loop in PowerShell

The ‘Do While’ loop in PowerShell is a type of loop that executes a block of code as long as a specified condition is true. This means that the block of code will always execute at least once, even if the condition is initially false. The syntax of the ‘Do While’ loop is as follows:

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

The ‘Do’ keyword is used to start the loop, and the code inside the curly braces is the block of code that will be executed. The ‘While’ keyword is used to test condition that needs to be met for the loop to continue executing. When the loop is first entered, the code block is executed once. Then, the condition is checked. If the condition is true, the code block set of commands is executed again. This process continues until the condition becomes false. You can also use multiple conditions in a do-until loop by combining them with logical operators such as -and or -or.

Here is an example of a simple do-while loop that counts down from 1 to 5:

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

In this example, the loop starts by initializing the variable $i to 1. The code block inside the loop then writes the current value of $i to the console, and increments the value of $i by 1. The condition $i -le 5 is then evaluated. If the condition is true, the loop will execute again, repeating the code block and the check of the condition. If the condition is false, the loop will exit, and the script will continue executing the next line of code.

The output of this code will be:

1
2
3
4
5
do while in powershell

Here is another example with the “Ne” operator. Here, the do-while loop continues executing the script block as long as the $counter variable is not equal to 5.

$counter = 0

do {
    # Code to be executed within the loop
    Write-Host "Counter: $counter"
    
    # Increment the counter
    $counter++
    
} while ($counter -ne 5)

The ‘Do Until’ Loop in PowerShell

The Do Until loop is a variation of the Do While loop found in many other programming languages. The primary difference between the two is that the Do Until loop executes until a specific condition evaluates to True. In contrast, the Do While loop executes as long as a particular condition evaluates to True.

The syntax of a PowerShell Do Until loop is straightforward. The keyword “Do” is followed by a block of code to execute. The block of code can contain any valid PowerShell commands, including other loops, conditionals, and functions. After the block of code, the keyword “Until” is followed by the condition to check.

Do {
   #Code to be executed
}  Until (condition)

The condition in the parentheses should be a comparison operator that evaluates to False initially, so the loop can execute at least once. The code inside the curly braces will continue to execute until the condition evaluates to True. Here’s an example: Suppose you want to print the numbers from 1 to 5. You can use a Do Until loop to achieve this as follows:

$counter = 1
Do 
{
   Write-Host "Counter value: $counter"
   $counter++
} Until ($counter -gt 5)

In the example above, the Do Until loop continues to run until the counter reaches the value of five. Once the counter equals 5, the condition becomes True, and the loop exits.

do until in powershell

The command block inside the Do loop will be executed at least once, regardless of whether the condition is true or false. The condition is checked at the end of each iteration of the loop. If the condition is false, the loop will continue to execute. If the condition is true, the loop will exit, and the code execution will continue after the loop.

Suppose you want to take user input until the user enters a valid input. You can use a Do Until loop to achieve this as follows:

Do {
    [int]$input = Read-Host "Enter a number between 1 and 10"
} Until ($input -gt 0 -and $input -le 10)

Here, we have used a Do Until loop to take user input until the user enters a number between 1 and 10. The $input variable is initialized with the user input using the Read-Host cmdlet. The condition in the Do Until loop checks if the input is between 1 and 10. If the input does not match, the loop will continue to execute, and the user will be prompted to enter a valid input again. Here is another example:

Do {
    Write-host "Waiting for WebClient Service to Start..."
    Start-Service -Name WebClient
    Start-Sleep -Seconds 5
} Until ((Get-Service -Name WebClient).Status -eq "Running")

In the above script example, the Do Until loop will continue to execute until the WebClient service is running. The loop will start the service and then wait for five seconds before checking the service status again.

Using Break and Continue in Loops in PowerShell

In PowerShell, you can use the break and continue statements within loops to control the flow of execution.

  • Using the ‘Break’ keyword to exit the loop prematurely, based on a certain condition.
  • Using the ‘Continue’ keyword to skip the current iteration of the loop, based on a certain condition.

Here’s an example of how you can use break and continue in these loop constructs:

# Example with break statement in do-while loop
$count = 1
do {
    Write-Host "Iteration: $count"
    if ($count -eq 3) {
        break  # Exit the loop when count equals 3
    }
    $count++
} while ($true)

# Example with continue statement in do-until loop
$count = 1
do {
    if ($count -eq 2) {
        $count++
        continue  # Skip the current iteration when count equals 2
    }
    Write-Host "Iteration: $count"
    $count++
} until ($count -gt 5)

In the first example, a do-while loop is used with the condition ($true) to create an infinite loop. Within the loop, the value of $count is checked as an exit condition, and when it equals 3, the break statement is encountered, causing the loop to exit.

In the second example, a do-until loop is used with the condition ($count -gt 5) to continue until $count exceeds 5. Inside the loop, the value of $count is checked, and when it equals 2, the continue statement is encountered, skipping the current iteration and proceeding to the next iteration.

The break statement is used to immediately exit the loop, while the continue statement is used to skip the remaining code within the loop for the current iteration and move to the next iteration.

Differences Between ‘Do While’ and ‘Do Until’ Loops in PowerShell

The ‘Do While’ and ‘Do Until’ loops are similar in structure, but they differ in their condition checking. The ‘Do While’ loop will continue to execute the code block as long as the condition is true, while the ‘Do Until’ loop will continue to execute the code block as long as the condition is false.

Let’s take a look at an example to illustrate the differences between the two loops. In the below example, we will prompt the user to enter a number, and the loop will continue to prompt the user until they enter a number greater than 10.

# Do Until Loop
Do {
    [int]$number = Read-Host "Please enter a number > 10"
} Until ($number -gt 10)

# Do While Loop
Do {
    [int]$number = Read-Host "Please enter a number < 10"
} While ($number -le 10)

In the Do Until loop, the loop will continue to execute until the user enters a number greater than 10. In the Do While loop, the loop will continue to execute while the user enters a number less than or equal to 10.

Best Practices for Using the ‘Do While’ and ‘Do Until’ Loops in PowerShell

When using the ‘Do While’ loop in PowerShell, it is important to follow some best practices to ensure that your code is efficient and effective. Here are a few best practices for using the ‘Do While’ loop:

  • Always specify a condition that will eventually become false, to avoid infinite loops. Test the condition thoroughly to ensure that the loop will terminate.
  • Use clear and concise variable names to make your code more readable.
  • Use comments to explain the purpose of your code and any complex logic.

Common Mistakes to Avoid

When using the ‘Do While’ loop in PowerShell, there are some common mistakes that you should avoid. Here are a few common mistakes to watch out for:

  • Forgetting to initialize the loop variable before entering the loop.
  • Forgetting to update the loop variable inside the loop, which can cause an infinite loop.
  • Using a condition that always evaluates to true, which can also cause an infinite loop.

Conclusion

PowerShell’s loops are a powerful tool that can be used to automate processes and tasks. They can be used to iterate over objects and arrays, wait for a certain condition to be met, or monitor services. They can also be used to automate processes, such as logging in to multiple systems or checking for new data. The Do While loop is used when you want to execute a set of instructions until a certain condition is met, while the Do Until loop is used when you want to execute a set of instructions until a certain condition is false.

When using PowerShell while loops, there are a few best practices to keep in mind. Make sure to use the correct syntax, use the correct condition, set the initial value, use the correct type of loop, and use the appropriate methods for troubleshooting. By mastering PowerShell while loops, you can automate processes and tasks and make them much more efficient. With the right knowledge and understanding, you can quickly become an expert in this powerful tool. Here is another post on How to use ForEach Statement and ForEach-Object Loop in PowerShell?

How to Create an Infinite Loop in PowerShell?

To create an infinite loop in PowerShell, you can use the “while” loop with a condition that is always true. For example:
$i=1
While ($true) {
# Code that executes indefinitely
Write-host $i
$i++
}

You can terminate an infinite loop by pressing Ctrl+C.

How do I loop an array in a PowerShell script?

To loop through an array in a PowerShell script, you can use a foreach loop. Here is an example:
$Array = @("item1", "item2", "item3")
foreach ($item in $Array)
{
# Code to be executed for each item in the array
Write-Host "Processing item: $item"
}

How do I skip a loop iteration in PowerShell?

In PowerShell, you can use the “continue” statement to skip the current iteration of a loop and move on to the next one. Here’s an example:
For ($i = 1; $i -le 5; $i++) {
if ($i -eq 3) {
continue # Skip the current iteration when $i equals 3
}
Write-Host "Iteration: $i"
}

How do you break a loop to stop?

You can use the “break” keyword to exit a loop and stop its execution. When the “break” keyword is encountered within a loop, the loop will immediately terminate, and the program will continue executing from the next line after the loop. E.g.
foreach ($item in $collection) {
if ($item -eq "stop") {
break # Exit the loop when $item equals "stop"
}
Write-Host "Processing item: $item"
}

What is the difference between do while and while loop in PowerShell?

In PowerShell, the main difference between a do while loop and a while loop is that a do while loop will always execute the code block at least once, even if the condition is initially false. On the other hand, a while loop will only execute the code block if the condition is initially true.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. Passionate about sharing the deep technical knowledge and experience to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *