PowerShell for Loops Simplified: Windows Sys Admin 101

powershellforloopsAutomation and scripting skills are essential for IT system admins today. If you are a Windows system administrator, chances are you’ve already heard of PowerShell.  It’s one of the most essential tool in an system administrator’s tool kit. PowerShell is Microsoft’s command-line shell and scripting language. You can use it for system administration purposes, by creating your own scripts to control and automate your Windows systems. You can also use PowerShell to work on desktops remotely, because the language supports Windows Management Instrumentation (WMI).

Today, you’re going to learn how to script FOR loops with PowerShell. If you have Windows 7, PowerShell 2.0 should already be installed on your system. To run the newest version of PowerShell (3.0), you need to have .NET Framework 4.0 installed on your PC.

PowerShell FOR Loops

If you have studied other programming languages, like C#, PL/SQL or Java, you know that you can get a body of code executed multiple times using the “FOR” loop. PowerShell too supports the FOR loop function. The basic syntax of a PowerShell FOR loop is:

for (initialize; condition; increment)
{ code to be executed }

Initialize: You can create and set a variable with a starting value, or, in other words, initialize it. You can also initialize or set one or more variables by separating them with commas. The conditional code will be evaluated based on the value of the variables you initialize.

Condition: The condition is tested each time by PowerShell before it executes the subsequent body of code. If the condition is found to be true, your body of code will be executed. If the condition is found to be false, PowerShell stops executing the code. The condition takes on a BOOLEAN true or false value.

Increment: In this section, you specify how you want to variable to be updated after each run of the loop. This can be an increment or a decrement or any other change you need. After the code has been executed once, PowerShell will update your variable.

The FOR loop keeps on looping until your conditional turns false. Let’s look at some examples.

Example 1

for ($i=1; $i –le 3; $i++)
{Write-Host $i}
Output:
1
2
3

Here you have initialized your variable “i” to 1. The condition is that as long as your variable “i” is less than or equal to 3, you print the value of “i” on screen. The value of the variable gets incremented by 1 each time, since you have used the ++ operator. The result will be displayed on your screen as 1,2,3: the values your variable takes.

Example 2

Let’s try some variations. You can do the same example in another way, by declaring your variable outside the body of the “for” condition. For example:

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

Notice that you still have to use the semicolon character “;” even if you don’t initialize the parameter within the “for” statement.

Infinite For loop

If you forget to use the semicolon character “;”, which acts as a delimiter, you will be stuck in an infinite for loop. For example:

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

Here, you have to manually break the code execution, by pressing “Ctrl+ c”.

Example 3

If you have a large amount of code to be written, you can use carriage return (skipping to a new line) to keep your code readable. For example:

for ($i=1
$i –le 3
$i++)
{Write-Host $i}

You can omit the semicolon character if you skip to a new line.

Comparison Operators: We have use the comparison operator –le in our sample programs, which checks whether the variable value is “less than or equal to” the value given. You can also use other operators in PowerShell, like –gt( greater than), -lt(less than), -ge(greater than or equal to), -ne(not equal to) and –eq(equal to) to write your FOR loops as required.

PowerShell For Loops used with Arrays

PowerShell For loops can be used with Arrays. If you’ve been programming for a while, you probably know and have used arrays before. If not, this would be a good time to step back and learn some basic programming concepts. In the most basic terms, an array is nothing but a collection of variables stored in an indexed form. A basic array of 3 integer numbers would be:

$integers= @ (1, 2, 3)

The “@” keyword lets PowerShell know that the variables within the brackets are to be treated as part of an array. Arrays are indexed starting from the number 0. Now, if you wanted to print the numbers (or string variables) within the array, you can use the PowerShell For loop:

$integers= @ (1, 2, 3)
For ($i=0; $i – le $ints.Length -1; $i++)
{Write-Host $ints[$i]}
Output:
1
2
3

In the initialization section, we declared the value of “i” as 0, instead of 1 like in our earlier examples. That is because arrays are indexed starting from the number “0”, and not the number “1”. If we start our loop our “i” as 1, our output would have been “2” and “3”.

The $int.Length holds the length of the array- it tells PowerShell the number of the members of an array. If we look at our program, the length of our array is 3. Now, the –le operator tells PowerShell to print until the value of “i” reaches 3. But because we have initialized the value of “i” as 0, we have to subtract 1 from the length of the array (- le $ints.Length -1).

Sounds complicated? You can use the foreach loop to make the above code simpler. The foreach loop lets you traverse through the members of a collection of objects (typically an array) and perform commands against each member of an array.

Do not use For loops in PowerShell if you want your program to  perform functions after a complicated series of instructions have been satisfied. PowerShell provides other types of loops you can use for that functionality, like the ForEach-Object loop, do while loop, while loop and do until loop. Only use PowerShell For loops when you want to execute a body of code a certain set number of times! This will make your code much less complex and improve code readability.

Remember, nothing works better than actually coding and trying things out for yourself. Mastering PowerShell is your first step towards climbing the ladder as a Windows system administrator. Make sure you get it right.