More PowerShell Constructs and Loop Management

 Mar 21, 2016

In a previous article I talked about some of the main PowerShell constructs – the If, Switch and the ForEach constructs. Let’s continue on in that vein, and talk about some of the other PowerShell constructs and flow control managers – the Do…While and Do…Until, the While, the For, the Break and the Continue statements.

The Do Construct

The Do construct can be used with the optional Until or the While parameters, and is basically the reverse of the If construct – where the If construct syntax is:

        If (condition is evaluated as true) {action(s) to be taken or cmdlets to be run if the condition is True}
the Do construct is:

        Do {action(s) to be performed} Until (a condition to be evaluated)

        $a= 1
        Do {Write "This is Pass $a `n"; $a++} Until ($a -eq 5)

Or

        Do {action(s) to be performed} While(a condition to be evaluated)

        $a = 1
        Do {Write "This is Pass $a `n";$a++} While ($a -ne 5)

(In the examples above, `n (using the grave character – the one below the ~) inserts a blank line; $a++ increments the value of $a by 1; -eq is the equals sign and –ne is the not equals sign in PowerShell). The condition must give either a True or False result, and be evaluated as True to stop the construct from looping again.

Note here that no matter what the condition is, the script block (the action(s) to be performed inside the curly braces) will always be run at least once. In the DO…Until loop, the script block will run once before the condition is evaluated, and will keep on repeating as long as the condition is evaluated as False. In the Do…While loop, the script block is run once and then repeated as long as the condition is evaluated as True. You see this when you run the script – you get This is Pass1, This is Pass 2, This is Pass 3 and This is Pass 4 on the screen, but no This is Pass 5 – why? Because the screen write is done, $a is incremented and THEN the condition is checked.

The Help File
HELP about_Do

The While Construct

Here again, the While construct is almost identical to the If construct in its syntax :

        While (condition to be evaluated) {action(s) to be performed whilst the condition is True}

The While construct will keep on looping so long as the condition is evaluated as True. As soon as the condition is evaluated as False, then the looping stops. e.g.:

        $a=1
While ($a -le 5) {Write "This is Pass $a `n";$a++}

The If construct is normally used to do a comparison, perform the associated action(s) and loop Until or While the comparison is evaluated as True, and you can use the ElseIf and Else to do a sequence of comparisons. The While construct is more useful if all you want to do is to create a simple infinite loop until such time as the condition is evaluated as True.

The Help File
HELP about_While

The For Construct

At first glance, the For construct seems to be more complicated than the constructs we have already looked at, but upon closer examination, it is actually quite straight forward, and is generally used to simply execute one or more cmdlets a predefined number of times. The syntax is as follows:

        For (<init>;<condition>;<repeat>) {action(s) to be performed}

The <init> section (initialize) above refers to the section of the For construct where you can put one or more cmdlets (separated by commas) that can be run before the loop begins. It is generally used to set the initial values of variables etc. The <condition> as before has to be evaluated to either a True or False result, and the <repeat> is one or more cmdlets that are executed each time the For loop is processed. The big difference between the For construct and say the Do...Until or the Do…While constructs is that the cmdlet(s) in the For construct are executed after the condition is evaluated. So to use an example from the For construct’s help file:

        For ($i=1; $i -le 10;$i++) {Write-Host $i}

Here the variable $i is initially set to 1, the condition checks to see if it is less than or equal to 10, and the <repeat> section increments the value of $i by one. The contents of $i are then printed and the loop continues until the condition is evaluated as False. As other possibilities the $i=1 can be set before the For construct, and the ;$i++ can be placed in the action script block (as in the example below, which give the same result as the previous example).

        $i=1
        For (;$i -le 10;) {Write-Host $i;$i++}

The minimum required is the parenthesis surrounding the <init>;<condition>;<repeat> sections and at least one cmdlet surrounded by the curly braces. The For construct can also be used to iterate values from an array as well, (such as in the following example), but the ForEach construct, described in my previous article can sometime give a simpler syntax.

        $items = @("One","Two","Three")
        For ($i = 0; $i -lt $items.Count; $i++) {$items[$i]}

The Help File
HELP about_For

The Break and Continue Constructs

O.K. so all those constructs are great for creating quite a number of different types of loops, but sometimes you want to skip some or even all of the processing of your loop, if certain conditions are met, and this is where the Break and the Continue come in.

The Break statement is used to “break out of” or to exit a loop when a certain condition is met to prevent further unnecessary processing of the loop, saving time and processor resources, and also as way out of an infinite loop (not normally a recommended practice, but when nesting loops it can be easy do by mistake). It can be used with any of the looping constructs, and the Switch statement, and is more commonly used when you start to nest your loops. For example, the following image shows a For loop that counts up to 10, but the inner condition (the If and ElsIf constructs) vary the output if the count equals 5. Note that in the following examples I have now placed the curly braces on separate lines and used indenting – this makes nested loop cmdlets easy to recognise.

In the next image, note how we can change the loop processing and the output just by adding the Break statement.

And here is an example of using the Break statement in the Switch construct, again to exit when a condition is met, and to prevent further unnecessary loop processing – in this case only the first drive type found is displayed.

In more advanced scenarios, the Break statement can also recognise labels, which allow the script flow to jump straight to a pre-defined label if the Break statement is run. Further details can be found in the help file.

The Continue statement causes you to abort the current loop process, and return to the start so that you can continue the loop processing, and is useful if you wish to skip certain conditions. The Continue statement can also supports the use of labels. In the following example I have used the Continue statement to simply skip the number 5 in a count sequence.

The Help Files
Help about_Break
Help about_Continue

So there you have it – a simple introduction to PowerShell constructs and statements and the concepts of looping and flow control in your scripts. Good luck with your own scripts, and if at first it doesn’t work, Keep Calm and Use Get-Help!

How do your Excel skills stack up?   

Test Now  

About the Author:

Gordon Cowser  

With over 22 years real world and training experience, Gordon is our most senior IT Infrastructure trainer. His expertise includes but is not limited to; Microsoft Server and Client OS, Messaging, Collaboration, Active Directory and Network Infrastructure. Gordon also specialises in SharePoint technologies training in both technical and end user aspects. With his extensive skill-set he brings a thorough mentoring capability to the classroom where he can advise on technical issues and challenges often beyond the scope of the course curriculum. A very approachable and experienced training professional, he has the ability to establish credibility fast with students at all levels.

Read full bio
top
Back to top