PowerShell Scripting: For Loops

powershell for loopsPowerShell includes support for many constructs that are common to most scripting and programming languages. Conditional logic, variables, functions, dynamic typing, and loops can all be used from PowerShell scripts. This is a short guide to the two types of for loop, and how you can use them in PowerShell.

Complete beginners to PowerShell scripting will find a more comprehensive tutorial of the system and its scripting language in PowerShell: A Getting Started Guide for IT Admins, and additional information concerning setting up a development environment and running scripts on multiple machines in an organization is covered in PowerShell for the Enterprise Desktop at Udemy.com.

The purpose of the basic for loop is to run a predefined sequence of instructions a set number of times. Programmers who are familiar with other languages will find that the declaration of a PowerShell for loop and its component parts are very similar to those they may have worked with previously.

The for loop looks like this:

for ($i=1; $i -le 10; $i++) {
    Write-Host "Item" $i; 
}

Three parameters make up the declaration of the loop, each separated by a semicolon:

  1. Initialization – the starting condition of the loop. Commonly used to define a variable and set its initial value.
  2. Condition – the expression provided should evaluate to either true or false, and the loop continues for as long as this condition is true.
  3. Repeat – a statement that is executed at the end of every iteration of the loop. This is typically used to increment the variable defined in the initialization.

In the example above, the loop defines a variable $i which starts at one and is incremented at the end of every iteration of the loop. The condition specifies that the loop should run while $i is less than or equal to 10. The sequence of instructions that will be executed on each iteration of the loop is placed within curly braces, immediately following the loop’s declaration.

As the repeat parameter, you can use unary operators to increment or decrement the variable $i by one. $i++ is the equivalent of the assignment statement $i=$i+1. For loops can move in increments larger than one by using expressions such as $i=$i+2 or $i=$i+10, and can also count down or backwards as shown in the example below:

for ($i=10; $i -ge 1; $i--) {
    Write-Host "Item" $i;
}

Setting the Condition

One of the key differences between the for loop in PowerShell scripting and its use in other languages occurs in the condition parameter. PowerShell has a different syntax for the operators needed in the expressions:

OperatorPowerShell SyntaxC Equivalent
Equals-eq==
Greater than-gt>
Greater than or equal to-ge>=
Less than-lt<
Less than or equal to-le<=
Not equal to-ne!=

 

The subtle difference between -lt and -le (or -gt and -ge) can be a source of small problems in your scripts. The declaration for($i=0; $i -lt 10; $i++) will run the loop ten times, from 0 up to (but not including) 10. However, the declaration for($i=0; $i -le 10; $i++) will loop eleven times – while the variable $i is less than 11.

The operators listed above are among the most common found in for loops. However, PowerShell supports quite an extensive range of operators that can be used here, including case sensitive operators and ones for matching patterns of characters in strings.

Foreach

For loops can be used for iterating through arrays – examining each item in turn – and given the large number of cmdlets that return arrays and collections, it is a technique that is used often.

For example, you can retrieve the file listing of the current directory using the cmdlet dir, and to iterate through each item in the current directory you can use a for loop, counting from zero to the number of items in the list:

$files = dir;
for ($i=0; $i -lt $files.length; $i++) {
    Write-Host $files[$i];
}

An alternative, simpler, syntax exists for accomplishing the same task: the foreach loop. This construct runs the code between curly braces for each item in the specified array or collection. On each iteration, the current item is placed in the named variable.

The example below uses the foreach loop to accomplish exactly the same function as the preceding example:

foreach ($i in dir) {
    Write-Host $i;
}

Break and Continue

It is often convenient to terminate a loop early when certain conditions are met; especially when no further work would be done, and so continuing to loop would be a waste of processor time. You can use the break statement for this – it causes an immediate exit from the loop and so no further code is run from the sequence specified in curly braces.

This is demonstrated in the code sample below. Even though the loop is declared to run 20 times, the break statement is used to exit the loop after only 10 iterations. The last value of $i is output to the console after the loop is terminated, in this example, it is 11.

for ($i=1; $i -le 20; $i++) {
    if ($i -gt 10) {
        break;
    }
    Write-Host $i;
}
Write-Host "END AT" $i;

Break can be used from a regular for loop, or from a foreach loop. It is especially helpful when using a loop to search through an array – once the desired item is found, there is no need to continue looping.

The continue statement also skips the remaining code in curly braces, however, it does not end the loop. Instead, continue tells the script interpreter to re-evaluate the loop’s condition and, if possible, begin again from the start of the code in braces.

The example below is similar to the preceding one, however, the end value of $i indicates that, even though only the numbers 1 through 10 are sent to the console, the loop continues until $i reaches 21.

for ($i=1; $i -le 20; $i++) {
    if ($i -gt 10) {
        continue;
    }
    Write-Host $i;
}
Write-Host "END AT" $i;

When working with loops that count until set value is reached, it is a common mistake to write a loop that will never terminate. A well-placed break statement can exit these infinite loops, but in situations where no break statement is present and the loop does not terminate, you can manually end the entire script by pressing Control + C, or closing the PowerShell console.

Looping from the Console

On occasion, it may be useful to write a loop directly into the PowerShell console rather than in a script. You can do this by ignoring line breaks and entering everything onto one line, and then pressing Enter to run the loop:

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

Other Loops in PowerShell

For and foreach loops are two of PowerShell’s looping mechanisms that are particularly well-suited for processing arrays and collections, or for executing code a preset number of times. There are also three other types of loop in PowerShell – Do…While, Do…Until, and While. These loops are explained in detail in PowerShell: A Getting Started Guide for IT Admins, which also contains further examples of the loops discussed here.