Monthly Archive

Categories

PowerShell for loop

Loops are a construction seen in most scripting and programming languages. A loop is used to repeat a set of statements a set number of times or until a specific criterion is met or while a specific criterion is true. In this post I’ll describe the PowerShell for loop.

For loops are found in many languages. A for loop is sometimes referred to as a counting loop as it will have a counter that starts at a pre-set value and counts up to a specific value. The counter is usually incremented by 1 for each iteration of the loop.

A PowerShell for loop looks like this

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

The counter – $i – is initialised to 1. The loop will execute while $i is less than or equal to 10 and $i is incremented by 1 for each turn round the loop. In this case the loop lists the value of the counter.  You can see the results like this

PS> $results = for ($i=1; $i -le 10; $i++){$i}
PS> "$results"
1 2 3 4 5 6 7 8 9 10

You can also run loops where the counter decreases

PS> $results = for ($i=10; $i -ge 1; $i--){$i}
PS> "$results"
10 9 8 7 6 5 4 3 2 1

A for loop is great when you need to perform the loop and exact number of times but if your loop depends on a specific criterion you’re better off using a while loop or a do loop which I’ll cover in another post

Comments are closed.