fbpx
PowerShell Training: The “Do…Until” Loop
By Gabriel Taylor
Published December 30, 2015
Estimated Reading Time: 4 minutes

Summary

 

This post describes how to use the “Do…Until” loop in PowerShell scripts.

 

Introduction

 

Happy Holidays, everyone. One truth I’ve encountered in the IT field is that the week between Christmas and New Years’ Day is nigh-universally both a production freeze and a time with the most staff out on vacation. With “so little” to do around the office, it is often the perfect time to catch up on the daily chores, preferably by adding some automation to take care of the chores instead. Speaking personally, my chore list has flooded with new tasks after the the historic rainfall we received in St. Louis over the holiday weekend. As I liberated my floundering basement of another wet/dry-vac-full of water earlier in the week, I thought about how repetitive the task was and how nice it would be to simply write a script to take care of the task for me. While the standard cmdlets shipping with PowerShell 5.0 don’t yet allow me to programmatically interact with reality, a combination of the process and some imagination offers a great opportunity to illustrate the capabilities the “Do…Until” loop can lend to help script away more IT-focused tasks.

 

Loopy Logic

 

The “Do…Until” loop is one of several types of loops PowerShell supports. Quite simply, the construct enables PowerShell to repeat some action defined in the script automatically until a predetermined exit condition is met. This is represented in the script like so:

 

do {

## action to repeat goes here

}
until ( <# stop condition goes here #> )

 

The type of action to repeat can be anything you want to place in the do {} script block – delete files, run a cleanup task, create virtual machines, move data, et cetera. For our illustration, let’s define that action loosely as “drain the water from the basement” and the predetermined exit condition as “when the water is gone”. Generally speaking, the situations in which to use a “Do…Until” loop are those where the exit condition is a known entity (“when the water is gone”) but the amount of work to be performed, meaning the number of loops which will need to be ran in order to complete the task, is unknown before the loop begins (the total quantity of water to move is unknown and/or changing). If you have a known quantity beforehand, e.g. “perform X action against each of the computers in Y array”, a “Foreach” loop is often a better fit. If you are trying to limit how many computers are processed in a given timespan, though, a “Do…Until” can provide the means to complete the task.

 

Also, note that the exit condition is bottom evaluated, meaning that the exit condition is evaluated after each iteration of the loop completes, not before. What this means is that, if the exit condition is already true before the loop begins, the “Do…Until” loop will still perform one iteration before stopping.

 

Hypothetically Speaking

 

As mentioned above, the talented engineers at Microsoft have yet to ship any cmdlets out of the box which are capable of redefining reality. For our illustration, though, let’s pretend we were able to get our hands on a pre-release version of a new PowerShell module NASA is creating to enable script-based interaction with reality. (Editor’s note: we have no knowledge about NASA’s capabilities or lack-thereof to programmatically interact with reality with nothing more than a personal computer. Requests for comment have received no official response.) In this hypothetical module, one can assume that a cmdlet exists to query a region of space-time for the existence of specific elements or chemicals, and perhaps other cmdlets for interacting with the query results. With a little time, another talented scripter could leverage those cmdlets to create functions to interact with specific elements or chemicals, good ol’ dihydrogen monoxide for example, or as it’s better known, “water”.

 

Automating the Dehydration

 

Armed with those functions, we can script the removal of water from the basement like so:

 

Get-Water -Location "Basement" | Remove-Water

 

Of course, since water is actively pouring into the basement, we aren’t able to submit the command once and call it done. Instead, we need the script to wait, check how much water is present (in order to catch any water still draining in), and repeat the action until the water level is back under control. To do that, we’ll add the “Do…Until” loop, along with some code to wait and measure if more water comes in, setting the exit condition to match when we’ve reached peak dryness, like so:

 

do {
## Get any water in the basement and remove it
Get-Water -Location "Basement" | Remove-Water

## Wait two minutes
Start-Sleep -Seconds 120

## Measure the remaining percentage of water in the basement and store it in a variable
$RemainingWater = Get-Water -Location "Basement" | Measure-Object | Select-Object -ExpandProperty "Count"
}
until ($RemainingWater -eq 0)

 

 

Conclusion

 

With that, we now have a “Do…Until” loop which will keep iterating until all water is gone from the basement after a two minute period! Now if we want to get really technical, we’re not accounting for the quantity of water which should be in the basement – the water vapor in the air, the water in the heater, pipes, et cetera. Before rolling this into production, we’d want to define what the normal basement conditions are and then adjust our logic accordingly or target our water removal more precisely. For the time being, however, this example illustrates how to leverage a “Do…Until” loop to automate repetitive tasks and help plug the flow of chores pooling in your to-do box.

 

Until next time, stay dry and keep automating your chores away! I’ll just keep hoping NASA gets back to me soon about that PowerShell module.

Article By Gabriel Taylor
With over 12 years of experience in the IT industry, Gabriel brings a focus on repeatable processes, solution design, and quality execution to Model’s Project Services practice. He believes the true value of technology is how it enables businesses to gain efficiencies, increase productivity, and achieve their goals. He is proud to work with Model’s team of experts to bring those benefits to Model’s clients.

Related Posts