PowerShell’s Do-Until loop allows actions to be repeated until a specified condition is met. In a Do-Until loop, the statements within the block are executed at least once before the condition is checked. This makes it different from other loops, where the condition is evaluated before any statements are executed.
In this PowerShell tutorial, I will show you how to work with PowerShell Do-Until with some real examples.
Introduction to PowerShell Do Until Loop
The Do Until loop in PowerShell is useful for repeatedly executing a code block until a specific condition becomes true. Unlike other loops, it ensures the code runs at least once before the condition is checked.
In the Do Until loop, the condition is checked after the code has been executed, meaning it will always execute at least one iteration. This differs from the While loop, which checks the condition before execution.
Here is a simple example of a Do Until loop in PowerShell:
$count = 0
Do {
$count++
Write-Output "Count is $count"
} Until ($count -ge 5)In this code, the block runs until the $count variable reaches 5. The output will display the count from 1 to 5.
You can see the output in the screenshot below after I executed the script using VS code.

- Initialization: Set up any variables needed.
- Execution Block: The main code that runs each time.
- Condition Check: This happens after the execution block.
Here are some pros and cons of PowerShell’s do-until loop.
- Pros: Ensures at least one execution; useful for tasks needing an initial run.
- Cons: It may run longer than expected if the condition never becomes true.
Check PowerShell For Loop
Syntax and Structure of PowerShell Do-Until Loop
The Do-Until loop in PowerShell repeats a block of statements until a specified condition is met. This loop ensures that the script block runs at least once, even if the condition is initially true.
Basic Syntax
The structure of a Do-Until loop is straightforward:
Do {
# Script block - code to be executed
} Until (Condition)Explanation
- Do: Starts the loop and executes the script block.
- Script block: The set of statements to run.
- Until: Follows the script block and checks the condition.
- Condition: If true, the loop stops; if false, it continues.
Example
Here is the simple example.
$counter = 1
Do {
Write-Output "Counter value is $counter"
$counter++
} Until ($counter -gt 5)In this example:
- The loop will print the value of
$counter. - The loop stops when
$counteris greater than 5.
Notes
- The condition is evaluated after the script block runs.
- This guarantees at least one execution of the script block.
- Useful for tasks requiring a minimum of one run before checking the condition.
Working with Conditions in the Do Until Loop
As a developer, you should know how to work with conditions while working with PowerShell do-until loop. These conditions determine when the loop stops executing. You can use the comparison and logical operators in this loop.
1. Using Comparison Operators
Comparison operators are essential when creating conditions in a Do-Until loop. They help compare values and decide whether the loop should continue. Common operators include:
-eq(equal to)-ne(not equal to)-gt(greater than)-lt(less than)-ge(greater than or equal to)-le(less than or equal to) etc.
For example, to keep looping until a variable $i is greater than 5, you might use:
do {
$i++
} until ($i -gt 5)This loop increments $i until its value exceeds 5. In the same way, you can also use other comparison operators in the PowerShell do-until loop.
2. Using Logical Operators
Logical operators allow combining multiple conditions in a Do-Until loop in PowerShell. They include -and, -or, and -not. These Boolean operators can make conditions more complex in this loop.
For example, to loop until both $x is greater than 5 and $y equals 10, you can use:
do {
$x++
$y = Get-Random -Minimum 0 -Maximum 20
} until ($x -gt 5 -and $y -eq 10)In this case, the loop runs until both conditions are true. Using logical operators helps in handling multiple scenarios within a single loop condition.
How to Control Do Until Loop Flow
Now, let me show you how to use the Continue and Break statements in PowerShell to control the do-until loop flow. I will also show how to use the Exit and Return with an example.
1. Use Continue and Break
The Continue statement in PowerShell restarts the loop, skipping the remaining statements in the current iteration. This is useful when bypassing specific conditions within the loop body.
For example, in a loop processing a list of numbers, Continue can skip negative values and proceed with the next iteration.
# Define an array of numbers
$numbers = @(-5, 3, -2, 7, 0, -1, 8)
# Initialize an index to iterate through the array
$index = 0
# Use a Do-Until loop to process each number
Do {
# Get the current number from the array
$number = $numbers[$index]
# Check if the number is less than 0
if ($number -lt 0) {
# Increment the index and skip the rest of the loop body
$index++
continue
}
# Output the number being processed
Write-Output "Processing $number"
# Increment the index for the next iteration
$index++
} Until ($index -ge $numbers.Length)The Break statement exits the loop entirely. This is especially useful when a specific condition is met, and you no longer need to iterate through the remaining items. For instance, breaking out of a loop once a match is found in a string search.
# Define an array of strings
$items = @("apple", "banana", "cherry", "target", "date", "fig")
# Iterate through each item in the array
foreach ($item in $items) {
# Check if the current item is the target string
if ($item -eq "target") {
# Break out of the loop
Write-Output "Target item encountered. Exiting loop."
break
}
# Output the item being checked
Write-Output "Checking $item"
}
Write-Output "Loop has completed."I executed the above PowerShell using VS code and you can see the output in the screenshot below:

2. Use Exit and Return
The Exit statement ends the script or function immediately. It is often used when a critical error is encountered, and further execution is undesirable. Placing Exit within a loop causes the entire script or function to terminate, not just the loop.
# Define an array of records (using hashtables for simplicity)
$records = @(
@{ Name = "Record1"; Status = "OK" },
@{ Name = "Record2"; Status = "OK" },
@{ Name = "Record3"; Status = "Error" },
@{ Name = "Record4"; Status = "OK" }
)
# Initialize an index to iterate through the array
$index = 0
# Use a Do-Until loop to process each record
Do {
# Get the current record from the array
$record = $records[$index]
# Check if the current record's status is "Error"
if ($record.Status -eq "Error") {
# Output a message and exit the script
Write-Output "Error encountered in $($record.Name). Exiting script."
Exit
}
# Output the record being processed
Write-Output "Processing $($record.Name)"
# Increment the index for the next iteration
$index++
} Until ($index -ge $records.Length)
Write-Output "Script has completed."The Return statement is used within functions and scripts to stop execution and optionally return a value. When used in do until loops within a function, Return exits the function regardless of the loop’s position.
function FindFirstEvenNumber {
# Define an array of numbers
$numbers = @(1, 3, 5, 8, 7, 2)
# Initialize an index to iterate through the array
$index = 0
# Use a Do-Until loop to find the first even number
Do {
# Get the current number from the array
$number = $numbers[$index]
# Check if the current number is even
if ($number % 2 -eq 0) {
# Return the first even number
return $number
}
# Increment the index for the next iteration
$index++
} Until ($index -ge $numbers.Length)
# If no even number is found, return null
return $null
}
# Call the function and output the result
$firstEvenNumber = FindFirstEvenNumber
Write-Output "The first even number is: $firstEvenNumber"PowerShell Do-Until Examples
Now, let me show you a few examples of how to use do-until in PowerShell.
1. Simple do until loop
A basic example of using a Do-Until loop is for counting. Here is the PowerShell script that increments a variable until it reaches a specific value.
$i = 0
Do {
Write-Output $i
$i++
} Until ($i -eq 10)In this script, the variable $i starts at 0 and is incremented by 1 in each loop iteration. The loop runs until $i equals 10, outputting the numbers 0 through 9.
2. Data Collection and Processing
A Do-Until loop can also be used to collect and process data in PowerShell. For instance, imagine collecting user input until a valid entry is made.
Do {
$userInput = Read-Host "Enter a number between 1 and 10"
} Until ($userInput -match "^[1-9]$|^10$")
Write-Output "Valid input received: $userInput"This script continuously prompts the user for a numeric input between 1 and 10 until they provide a valid number.
3. File and Directory Operations
File and directory operations are another common use case. An example is checking if a directory exists and creating it if it doesn’t.
$directory = "C:\temp\logs"
Do {
If (-Not (Test-Path $directory)) {
New-Item -Path $directory -ItemType Directory
}
} Until (Test-Path $directory)
Write-Output "$directory is ready"This ensures the specified $directory exists, creating it if necessary, and confirms its existence before proceeding.
4. Working with Nested Loops
Here is another example, how we can use the nested loops with do until in PowerShell. By embedding a Do-Until loop inside another loop, the script can control its execution more granularly.
Consider a scenario where an outer loop processes a list of users, and an inner Do-Until loop retries a failed operation until it succeeds:
$users = Get-Content -Path "C:\users.txt"
foreach ($user in $users) {
$success = $false
Do {
Try {
# Try to perform an operation with $user
Invoke-SomeCmdlet -User $user
$success = $true
}
Catch {
Write-Output "Retrying for user $user"
}
} Until ($success -eq $true)
}In this script, the outer foreach loop iterates over each user, and the inner Do-Until loop retries the Invoke-SomeCmdlet until it succeeds.
Handle Errors within Do Until Loops
When using do-until loops in PowerShell, error handling is crucial to ensure smooth execution. Let me show you how to manage errors effectively within do until loops.
Try-Catch-Finally Blocks
A common method for handling errors is using try-catch-finally blocks. This allows script execution to continue even when errors occur. The try block contains the code that might fail, and the catch block handles the error.
do {
try {
# Code that might fail
Do-Something
}
catch {
Write-Output "An error occurred: $_"
}
} until ($success -eq $true)CmdLet Error Handling
CmdLets in PowerShell can use the -ErrorAction parameter to control error behavior. Setting -ErrorAction Stop forces CmdLets to stop and throw terminating exceptions, which can be caught in try-catch blocks.
do {
try {
Get-Item -Path "C:\MyFolder\File.txt" -ErrorAction Stop
}
catch {
Write-Output "Error: $_"
}
} until ($success -eq $true)Conclusion
PowerShell Do-Until loop runs a block of code until a specified condition is met.
Key Points:
- The loop ensures that the script executes at least once.
- The condition is evaluated after each iteration.
- It is effective for tasks like checking file status or waiting for a process to complete.
In this PowerShell tutorial, I have explained how to use the do-until loop in PowerShell with various examples.
You may also like:
Bijay Kumar is an esteemed author and the mind behind PowerShellFAQs.com, where he shares his extensive knowledge and expertise in PowerShell, with a particular focus on SharePoint projects. Recognized for his contributions to the tech community, Bijay has been honored with the prestigious Microsoft MVP award. With over 15 years of experience in the software industry, he has a rich professional background, having worked with industry giants such as HP and TCS. His insights and guidance have made him a respected figure in the world of software development and administration. Read more.