Powershell basics part 6 – Loops


Hello dear readers,
Sorry for the delay, because of Christmas I couldn’t post anything. By the way Merry Christmas to everyone, I hope you’ve enjoyed the holidays. In this post we will continue our journey discovering more interesting parts of Windows Powershell. Our main focus in this post is PS loops. Loops are used in scripting and in general programming languages for processing a piece of code over and over again. If you have encountered loops again then you know how important are they when writing code. We will talk about all the loops available in PS :

While the code is executed as long as a condition is met. The code is written under this statement
Do while – the code is executed as long as a condition is met. The code is written between do and while statements.
Do until – the code is executed until a condition is met.
For – the code is executed a number of times
Foreach – the code is executed for elements in a array or a collection.
Also we will talk a little bit about break and continue statements when working with loops.

How to use while loop:
while is used when a piece of code must be executed as long as a condition is fulfilled. The syntax of while statement is the following:

while (condition)   – the condition that has to be met
{
code                      – the code that is executed, it can be a single line or multiple lines of code.
}  

An example of using the while loop:

[int]$a = 4;                  – initializing variable a with value 4
[int]$b = 8;                  – initializing variable b with value 8
while($b -ne $a)           – while variable a is not equal to variable b execute the following:
{
$b–;                            – decrements variable b value
Write-Host $b;             – writes variable b value
}

Powershell script

You can find out more about while loop by writing Get-Help about_while in PS:

While statement Powershell

How to use do while loop:
do while is used to execute a piece of code as long as a condition is met. The difference between while and do while is that while executes the code after the condition is verified while do while executes the code first then the condition is verified. The code in do while statement is written between do and while. The syntax looks something like this:

do                              – the start of do while statement
{
code                           – the code that is executed, it can be a single line or multiple lines of code.
}
 while (condition)       – the condition that has to be met

To adapt do while syntax to our exercise from above we would write the following:

[int]$a = 4;
[int]$b = 8;
do
{
$a++;                        – this time the code is first executed then the condition is tested
Write-Host $a;
}
while($a -ne $b)

While Powershell

The do until statement:
You probably wondering why we use do until if we have the do while statement. Well do until is used to execute a code until a condition is met. It executes a code while the condition is false. When the condition becomes true then the do until statements ends.

do                            – start of statement
{
code                         – code to be executed
}
until (condition)      – end of statement. the code is executed until a condition is met

In order to get the same result in our example we would type the following:

[int]$a = 4;
[int]$b = 8;
do
{
$a++;
Write-Host $a;
}
until($a -eq $b)

Do until statement Powershell

 

More about do while and do until by typing Get-Help about_do:
Do while Powershell command
The for statement:
For is used to execute a piece of code until a condition becomes true. It is used generally when working with arrays. For statement uses the so called iterator to enumerate the values of an array. You will understand the meaning of iterator when we will write an example. The for statement looks something like:
for (start; condition; step)   – for statement
{
code                                    – code to be executed
}
As you see above for has three parameters, they are all optional because if you don’t put them the loop will execute over and over again until is manually stopped. The start parameter, as I wrote refers to the first position of the iterator, the condition is the one that has to become true and the step parameter refers to the number of hops executed at each iteration.
This example will clarify the for statement:
$array=@(3,5,7,8,10)      – declaration of the array with it’s values
$n=$array.length;            – n is the length of the array. in our example n is equal to 5 because we
                                        have 5 values in the array
for($i=0;$i -le $n;$i++)    – the for statement. the iterator starts at the position of 0 in our case
                                        array[0] is value 3. the condition that has to become true is that i has to
                                        to be lower or equal to n, in our case value 5. i++ is the number of
                                        steps that the for statement takes. this could be written as $i=$i+1
{
write-host $array[$i]        – the code to be executed, in our case write the value in the $i position
}
Powershell script
More about for statement by typing Get-Help about_for:
For loop Powershell
The foreach statement:
Used to execute a piece of code for items that are part of an array. The syntax of foreach statement looks like this:
foreach (item in array)   – for each item that is part of the array
{
code                               – execute the code
}
 
An example of foreach statement:
$array=@(3,5,7,8,10)              – array declaration
foreach($i in $array)                – for each item part of array
{
$i=$i+10                                 – increment item with value 10
Write-Host $i                          – write value
}
Foreach Powershell
More about the foreach statement can you find by typing Get-Help about_foreach:
Foreach statement Powershell
Using the brake and continue statements when working with loops.
Brake is used when you want to interrupt a code that is running and to execute the next code that follows. When break is used the loop ends. For example you want to execute a code but when you get to a certain value you want the code to be interrupted. I will show you what I mean in the following example:
$array=@(3,5,7,8,10)
$n=$array.length;
foreach($i in $array)
{
$i=$i+10
   if($i -gt 15)
     { break}
Write-Host $i
}
This example is like our foreach exercise except that when $i value gets greater then 15 the code ends and powershell will jump to the next line and will write the value of $i:
Foreach statement Powershell
Continue is used almost like break statement except that powershell doesn’t end the whole loop it just terminates executing the code at that particular moment. In our next example I will show you how continue can be used:
$array=@(3,5,7,8,10)
$n=$array.length;
foreach($i in $array)
{
$i=$i+10
   if($i -eq 15)
     { continue }
Write-Host $i
}
In the code above, powershell executes the code until $i gets at the value 15. At that point PS terminates executing that particular iteration and jumps directly to the next one. The result of our example is shown in the image below:
Powershell script
OK that is all about working with loops, we have covered the basics of this section. I hope this was an interesting post, if you have any question please don’t hesitate to comment. Have a nice day and stay tuned for more tutorials.
Advertisements

One thought on “Powershell basics part 6 – Loops

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s