The For loop is one of the most valuable tools in any programming language, and Microsoft PowerShell is no different. You can use other loops to repeat commands, but the For loop is perhaps the most straightforward.
From iterating over arrays to carrying out a function a predetermined number of times, there are many things you can achieve with this tool. Here is a tutorial on how to use For loops in PowerShell.
What Is the Use of For Loops in PowerShell?
Unlike Command Prompt, PowerShell is a complete scripting environment. This means you can write reusable PowerShell scripts to automatically carry out tasks rather than entering commands manually. And For loops are the key to writing these modules.
A For statement repeats a script block a specific number of times, modifying a given variable to keep track of progression. This allows you to use the loop for some rather interesting scenarios.
You can generate sequences of numbers, determine a prime number, or display a countdown timer. More practically, you can iterate over an array of objects, performing some action with each entry.
The Syntax of a For Loop in PowerShell
For loops work in Windows PowerShell the same way they do in any programming language. Expressions initializing the tracking variable, testing its value, and modifying the variable are ensconced within the brackets following “For,” separated by semicolons. Then comes the statement list itself bound by curly braces.
For (Initialization, Condition, Update,
How to Use the For Loop in a PowerShell Script
Using the For loop is pretty simple. Whenever you encounter a situation that calls for repeating a slightly varying step, you should put it into a For loop.
Let’s say you need to write a code snippet that can find the sum of all natural numbers until a number n, contained in the variable $n. Here is a basic For loop example:
$n = 10
$sum = 0
For ($i = 1 ; $i -le $n ; $i++)
$sum = $sum + $i
“The sum of $n natural numbers is $sum”
Accessing Arrays Through a For Loop
Generating numeric sequences is hardly what most people use PowerShell for. A more common usage is to iterate over an array.
Say you have an array $week with seven elements. You can output the list of the days contained in the array using a simple For loop, as demonstrated in the following example.
For ($i = 0 ; $i -lt $week.Length ; $i++)
Using the ForEach Loop To Quickly Iterate Through an Array
Another form of the For loop is the ForEach statement. This version simplifies going through the contents of a PowerShell array and processing them individually. The previous code snippet, for example, can be rewritten like this:
Foreach ($day in $week)
When dealing with more complex objects, you can also use the Foreach-Object cmdlet to perform an action on the contents of any PowerShell command.
How is the For Loop Different From Other Types of Loops?
The For loop isnt the only type of looping statement available to you. Like most programming languages, PowerShell has multiple types of loops.
The simplest of these is the While loop. All you have is a condition and a script block, and the loop runs as long as the test expression evaluates to true. Since the expression is evaluated first, there is a chance for the code not to run at all or end up as an infinite loop.
If you are writing a script that needs to run at least once – even if the expression evaluates to false—then you can use the Do-While loop. The only difference from the While loop is that it places the command block before the condition, which means that the code is executed before the test expression is checked for the first time.
Another version of this loop is Do-Until. Basically, it runs the code block and then repeats it until the test expression is true – the reverse of a Do-While loop. Not a particularly useful structure, as you can achieve the same thing by modifying the condition in a standard Do-While loop.
Why the For Loop is Better
The problem with all these other looping structures is that they do not include the initial value or update statements. You have to manually remember to create a variable outside the loop and then increment it (or decrement it) during every pass of the loop.
As you might expect, programmers often forget this step, leading to a script that doesn’t work as intended. This wastes precious time in debugging.
The For loop avoids this issue by necessitating the initialization and increment expressions within the starting brackets. This leads to cleaner, more robust scripts.
When Should You Use the For Loop in PowerShell?
PowerShell is all about creating scripts for automation. And probably the most useful tool for achieving this is the For loop. You can use it to replace many copy-paste operations with a more compact, elegant script.
The most common function of this loop is to iterate over an array, one entry at a time. For an even more streamlined script, you can use a ForEach loop as well. You can also use the For loop to generate numerical sequences, although that is rarely needed.
The For loop scores over other looping algorithms by including all essential functions of a loop into the parameters, preventing any errors due to forgetting those statements. This makes the For loop indispensable in any scenario calling for repeating a set of commands.