Learning PowerShell – Lesson Eight

Share:
PowerShell

PowerShell Lesson Eight

By: Steven Aiello

Teach Your Self PowerShell – Understanding PowerShell Loops

In the last two lessons we learned all about if, elseif, and else statements, these are great logic operators to use if you need to make a true false type choice. There are however times when you want your computer to do something over and over depending on the condition, this is where loops come into play.

Maybe you’re like me and you have a favorite song and you will play that song over and over until you get sick of the song. Maybe I’m just strange… However you can use that logic to make sense of a loop

While(not sick of song){

Play Song

}

Pretty simple isn’t it? This is exactly how loops work in scripts and programs; however there is more than just the While loop and knowing what one to use is important to make sure you receive the output you expect. Sometime you want a loop to execute at least once, sometimes you want to make sure a certain condition is met before a loop executes. Depending on what you want your code to do will determine the loop you choose.

In this lesson we are going to look at a few kinds of loops

PowerShell While loop

Let’s take a look at our first PowerShell While loop and see what’s going on.

A lot of this code should look pretty familiar to you except for line number three. You should be able to see we are assigning the variable “i” on line number two. In this case “i” is being assigned a value of one. Since “i” is not a string but a number we don’t put quotes around it.

By the way many programmers and scripters will use “i” as a counter variable because in mathematics “i” stands for index.

http://en.wikipedia.org/wiki/Summation

In the next line we have our While loop. What is it doing? Think about it in pseudo-code.

Line 2: Assign “$i” a value of 1

Line 3: While “$i” or 1 is less than 10 (remember that from homework two)

Line 4: Write-Host $i (so whatever the value of “i” is will be written to the screen)

Line 5: $i = $i + 1 (This is a little tricky but thing about it. You’re taking the current value if “i” add 1 and then assigning that value back to the “i” variable)

Back to Line 2: Check and see if “i” is still less than 10 and if not repeat

So based on what we see here PowerShell will keep printing out numbers until “i” is no longer less than 10. This is a very important concept to understand; take a few moments and play with the starting and ending values in the loop. What happens if you set “i” to 12? If you said the loop will never execute you are right because the expression in the while loop never evaluates to true. With a while loop you have control right from the state if the loop executes or not.

A very key point to understand about the While loop is that it runs when the condition is true and stops when the condition is false.

PowerShell Do While loop

Something that is closely related to the While loop is the Do While loop. Let’s write out some pseudo-code and see if you can spot the difference.

set_color = blue

do{

Write-Host set_color

}while(color equals red)

What happens and why? The key thing to remember is that when you use a Do While loops the condition will be evaluated after the statement executes the first time. This means that the code inside the loop will always execute at least one time.

See the difference in the resulting output? The number 12 is written out and then the evaluation is tested after the action in the code block. The condition is false so the loop does not continue. This is a very important concept to keep in mind when trying to understand what kind of loop to use. One thing that the while and the do while loops share in common is that they both execute when the condition is true and stop when the condition is false.

PowerShell Do Until Loop

The next loop we will look at is the do until loop. The main thing to note with a Do Until loop is that the loop continues while the condition is false, this is the exact opposite of the control the while and do while loops use. How does this work?

As you can see the output here is slightly different than before. In our previous do and do while loops the numbers on the screen only printed to nine. Why is this? Remember this loop runs until something is true and we are telling the do until loop to run until the variable “$i” is greater than 10. You need to make sure you’re very careful and test your loops or you can end up with serious errors in your code.

PowerShell For loop

The for loop is a compact way to write a loop; to people new to programming or scripting it can be slightly confusing because you’re taking a lot of what you would have done in other spaces and packing it all into one statement. Take a look at the highlighted parts of the image below:

Highlight on line 2: Sets the variable

Highlight on line 5: Adds one to the variable

Highlight on line 6: Tests the condition

The PowerShell for loop does this all in one line.

As you can see right on line number two all the actions we mentioned before are ececuted.

$i is set to the value of 1

The test condition is set and tested $i is less than 10

$i has one added to it each loop (Note $i++ is just another way of writing $i = $i + 1)

Everything we did in our while loop on three lines is done in one line with a for loop. A thing to remember is that a for loop also executes while something is true.

PowerShell Foreach loop

The last loop we are going to talk about deals with a collection of objects or values not just one. But you may ask the question: When will we have a collection of objects?

Get-Service

Remember how the Get-Service command sends all that information flying across the screen? If we need to process that data we can use the PowerShell foreach loop.

A lot of what’s displayed in the image should look familiar to you however there are a few key differences.

Line 2: Why does Get-Services have parenthesis around it with an @ symbol in front?

That’s because we’ve snuck in something else in a very sneaky way. Arrays! You just saw and array and it was that simple. An array is a way to put many things into one variable name. Variables are really very powerful. They can hold data, objects, and even many pieces of data or objects. In this case the variable:

$SERVICES

is actually holding many objects that are services.

Line 4: foreach does exactly what it sounds like. For each object in that list it will write out the name of that object. Remember we did the exact same thing in lesson six with the WHERE command? But what does is mean ($SERVICE in $SERVICES)? Again think in pseudo-code. We have a group or many services, however only want to act on one service per loop. So what PowerShell is doing is creating a temporary variable for itself and you to use. You get to assign that name anything.

Here is the exact same code except instead of calling that temporary variable $SERVICE we called is $i. You have complete control of what you name your service; however it is good practice to name your variables something that is descriptive so when you have to go back to your code later it makes sense.

So now you’ve gona through many of the loops in PowerShell. With these loops you can perform most any looping chores you will come up against. If you’re still wondering about arrays don’t worry we are going to cover them very soon.

Share:

Leave a reply

thirty eight − twenty eight =

This site uses Akismet to reduce spam. Learn how your comment data is processed.