Prof. Powershell

Just DO It!

Lesson in Logic #3: The secret to getting your script block to execute at least one time is the DO loop.

In our last lesson, we examined the WITH construct. One benefit -- or drawback, depending on the situation -- is that the script block may not execute. What if you want a script block to always execute at least once in a looping construct? You can accomplish this with a DO loop. This construct has two variations. You can DO something until a condition evaluates as true:

PS C:\> $x=5
PS C:\> do {$x
>> $x++
>> } until ($x -eq 10)
>>
5
6
7
8
9
PS C:\>

After I've set $x to 5, I use the DO keyword and then a set of curly braces. PowerShell will "do" whatever is in the curly braces <i>until</i> the parenthetical expression, <i>$x -eq 10 becomes true</i>. This example merely writes the value of $x to the console and increments $x by one each time through the loop.

As with the While loop we discussed before, you want to make sure your condition will eventually become true or you will be stuck in an infinite loop.

With this DO construct, you are guaranteed that the code block will execute at least once. Even if $x starts out as 20, the evaluation doesn't happen until after the code block as been executed.

The second DO variation executes a code block WHILE some expression is true:

PS C:\> $x=1
PS C:\> do {
>> $x
>> $x++
>> } while ($x -le 10)
>>
1
2
3
4
5
6
7
8
9
10
PS C:\>

The underlying principal is the same in both examples. The code block executes at least once before an evaluation is made. Whether you use WHILE or UNTIL depends on situation and what you are checking. Sometimes you will want to do something until a certain threshold is reached. Other times, you might want to loop while some conditition is True. For example, here's a better implementation of the While example from last time:

do {
  sleep -millisecond 500
} While ((get-service spooler).status -eq "running")

Write-host "The spooler service has stopped!" -foregroundcolor red

The end result is the same, but this syntax is a little easier to follow.

About the Author

Jeffery Hicks is an IT veteran with over 25 years of experience, much of it spent as an IT infrastructure consultant specializing in Microsoft server technologies with an emphasis in automation and efficiency. He is a multi-year recipient of the Microsoft MVP Award in Windows PowerShell. He works today as an independent author, trainer and consultant. Jeff has written for numerous online sites and print publications, is a contributing editor at Petri.com, and a frequent speaker at technology conferences and user groups.

comments powered by Disqus
Most   Popular

SharePoint Watch

Sign up for our newsletter.

Terms and Privacy Policy consent

I agree to this site's Privacy Policy.