Windows PowerShell 1.0 Looping with the for and foreach Statements

PreviousTable of ContentsNext
Windows PowerShell 1.0 Flow Control with if, else and elseifWindows PowerShell 1.0 Looping with do and while Statements


Purchase and download the full PDF version of this PowerShell eBook for only $8.99


In this chapter of Windows PowerShell 1.0 Essentials we will continue looking at flow control in Windows PowerShell scripts. In the preceding chapters we have looked in detail at using conditional statements to decide what code should be executed. Another aspect of flow control entails the definition of loops. Loops are essentially sequences of PowerShell statements which are to be executed repeatedly until a specified condition (or conditions) are met.

It is generally common knowledge that computers are great at performing repetitive tasks an infinite number of times, and doing so very quickly. It is also common knowledge that computers really don't do anything unless someone programs them to tell them what to do. Loop statements are the primary mechanism for telling a computer to perform the same task over and over again until a set of criteria are met. This is where for, while and do ... while loops are of use. This chapter is dedicated to the design of for and foreach loops in Windows PowerShell. The while and do ... while looping techniques will be covered in Windows PowerShell 1.0 Looping with do and while Statements.

The PowerShell for Loop

Windows PowerShell for loops are ideal in situations where the same sequence of statements need to be repeated a specific number of times. Suppose, for example, that you have a requirement to add a number to itself ten times. One way to do this might be to write the following PowerShell code:

$x=10
$x += $x
$x += $x
$x += $x
$x += $x
$x += $x
$x += $x
$x += $x
$x += $x
$x += $x
$x += $x
$x
10240

Whilst this is somewhat cumbersome it does work. What would happen, however, if you needed to perform this task 100 times or even 10,000 times. Writing a PowerShell script to perform this as above would be prohibitive. Such a scenario is exactly what the for loop is intended to handle.

The syntax of a Windows PowerShell for loop is as follows:

for ( ''initializer''; ''conditional expression''; ''loop expression'' )
{
      statements to be executed
}

<google>ADSDAQBOX_FLOW</google> The initializer typically initializes a counter variable. Traditionally the variable $i is used for this purpose. For example:

$i = 0;

This sets the counter to be the variable $i and sets it to zero.

The conditional expression specifies the test to perform to verify whether the loop has been performed the required number of iterations. For example, if we want to loop 100 times:

$i -lt 100;

Finally the loop expression specifies the action to perform on the counter variable. For example to increment by 1:

$i++;

The body of statements to be executed on each iteration of the loop are contained within the code block defined by the opening ({) and closing (}) braces.

Bringing this all together we can create a for loop to perform the task outlined in the earlier example:


$y=10

for ($i=0; $i -lt 10; $i++)
{
      $y += $y;
}

$y
10240

Creating an Infinite for Loop

A for loop which will execute an infinite number of times may be constructed using for (;;) syntax. For example, the following code sample will output Hello from Windows PowerShell until the program is manually terminated by the user (or the computer is turned off or rebooted):

for (;;)
{
   "Hello from Windows PowerShell"
}

Breaking Out of a for Loop

Having created a loop it is possible that under certain conditions you might want to break out of the loop before the completion criteria have been met (and particularly if you have created an infinite loop). One such example might involve continually checking for activity on a network socket. Once activity has been detected it will be necessary to break out of the monitoring loop and perform some other task.

For the purpose of breaking out of a loop, Windows PowerShell provides the break statement which breaks out of the current loop and resumes execution at the code directly after the loop. For example:

for ($i=0; $i -lt 10; $i++)
{ 

  $y += $y

  if ($y -gt 100)
  {
     break
  }
}

$y
160

In the above example the loop will continue to execute until the value of j exceeds 100 at which point the loop will exit.

Nested for Loops

So far we have looked at only a single level of for loop. It is also possible to nest for loops where one for loop resides inside another for loop. For example:

for ($i = 0; $i -lt 100; $i++)
{
     "i = $i"

     for ($j = 0; $j -lt 10; $j++)
     {
             "j = $j"
     }
}

The above example will loop 100 times displaying the value of i on each iteration. In addition, for each of those iterations it will loop 10 times displaying the value of j.

Breaking From Nested Loops with Labels

An important point to be aware of when breaking out of a nested for loop is that the break only exits from the current level of loop. For example, the following Windows PowerShell example will exit from the current iteration of the nested loop when j is equal to 5. The outer loop will, however, continue to iterate and, in turn execute the nested loop:

for ($i = 0; $i -lt 100; $i++)
{
     "i = $i"

     for ($j = 0; $j -lt 10; $j++)
     {
              if ($j -eq 5)
	      {
                   break
              }

             "j = $j"
     }
}

In order to break out of both loops it is necessary to use a label to designate the extent to which the break is to be effective. By placing a label above the outer for loop and then referencing it alongside the break statement we can break from both loop levels:

outerloop:
for ($i = 0; $i -lt 100; $i++)
{
     "i = $i"

     for ($j = 0; $j -lt 10; $j++)
     {
              if ($j -eq 5)
	      {
                   break outerloop
              }

             "j = $j"
     }
}


Continuing for Loops

Another useful statement for use in loops in the continue statement. When the execution process finds a continue statement in any kind of loop it skips all remaining code in the body of the loop and begins execution once again from the top of the loop. Using this technique we can construct a for loop which outputs only even numbers between 1 and 9:

for ($i = 1; $i -lt 11; $i++)
{
          if ($i % 2)
          {
               continue;
          }
           
          "i = $i"
}

In the example, if $i is not divisible by 2 with 0 remaining, the code performs a continue sending execution to the top of the for loop, thereby bypassing the code to output the value of $i. This will result in the following output:

i = 2
i = 4
i = 6
i = 8
i = 10

Windows PowerShell foreach Loops

The Windows PowerShell foreach statement provides a convenient mechanism for looping through the elements in a collection. The basic syntax for the foreach loop is as follows:

foreach ($variable in $collection) { statements to be executed for each element }

For example, to iterate through each element in an array:

foreach ($color in $colors)
{
     "current color is $color"
}

current color is red
current color is white
current color is blue

<google>BUY_WPS_BOTTOM</google>