PowerShell Training: The “Do…Until” Loop

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:

 

 

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:

 

 

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:

 

 

 

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.

By |2016-06-09T08:00:45+00:00December 30th, 2015|PowerShell, Uncategorized|0 Comments

About the Author:

Solutions Architect / Team Lead – Model Technology Solutions Gabriel specializes in SCOM, SCSM, Orchestrator, and PowerShell, along with experience in several Azure technologies and other server roles. Gabriel has spoken at several regional conferences and user group meetings about leveraging Microsoft’s datacenter and automation technologies to solve specific problems. Gabriel’s attention to detail and relentless pursuit of perfection may one day make his brain explode from information overload. Hopefully they will have a cure before then.

Model Technology

Let us help you get your end point and data center strategy on cruise control!  Ask about our Calibration Assessment.

CONTACT US

  • 12125 Woodcrest Executive Drive, Ste. 204 Creve Coeur, MO 63141
  • (314) 254-4138
  • sales@model-technology.com

RECENT TWEETS