PowerShell For Loop (With Examples)

A PowerShell for loop runs a block of code a set number of times. You give it a starting value, a condition and a step, and PowerShell repeats the block while the condition is true:

for (<init>; <condition>; <repeat>) {
    <statement list>
}

Here’s the simplest real example, counting from 1 to 5:

for ($i = 1; $i -le 5; $i++) {
    "Pass number $i"
}

Output:

Pass number 1
Pass number 2
Pass number 3
Pass number 4
Pass number 5

Below, you’ll see how each part works, how to loop from 1 to 10, step by 2, count backwards and walk an array by index. I’ll also cover break, continue, the mistakes I see most, and when foreach is the better choice.

I ran every example in PowerShell 7.6 and Windows PowerShell 5.1. The for loop behaves the same in both.

How the three parts of a for loop work

PartExampleWhen it runs
Init$i = 1Once, before the first pass
Condition$i -le 5Before every pass. The loop stops as soon as it’s $false
Repeat$i++After every pass, before the condition is checked again

Because the condition is checked first, the body may never run. for ($i = 10; $i -le 5; $i++) does nothing at all.

Microsoft’s about_For documentation describes the full syntax.

To walk through every item without a counter, use a foreach loop instead.

PowerShell for loop from 1 to 10

To loop from 1 to 10, start at 1 and keep going while the counter is less than or equal to 10:

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

Output:

1
2
3
4
5
6
7
8
9
10

When you just need the numbers and don’t care about the counter logic, the range operator 1..10 with foreach is shorter. This one builds server names with a two-digit number:

foreach ($i in 1..10) {
    "Server{0:D2}" -f $i
}

Output:

Server01
Server02
Server03
Server04
Server05
Server06
Server07
Server08
Server09
Server10

Count by 2 or count backwards

The repeat part doesn’t have to be $i++. Use $i += 2 to step by two, or $i-- with -ge to count down:

# count by 2
for ($i = 0; $i -le 10; $i += 2) { $i }

'---'

# count down from 5 to 1
for ($i = 5; $i -ge 1; $i--) { $i }

Output:

0
2
4
6
8
10
---
5
4
3
2
1
PowerShell for loop counting by 2 and counting down from 5 to 1 in Windows PowerShell 5.1
Stepping by 2 and counting down in Windows PowerShell 5.1

Loop through an array by index

This is where the for loop really earns its place. You get the position of each item, not just the item:

$states = 'California', 'Texas', 'Florida', 'New York', 'Ohio'

for ($i = 0; $i -lt $states.Count; $i++) {
    "{0}. {1}" -f ($i + 1), $states[$i]
}

Output:

1. California
2. Texas
3. Florida
4. New York
5. Ohio
PowerShell for loop printing each array item with its position
Looping through an array by index in PowerShell 7

Arrays start at 0, so the condition is $i -lt $states.Count, not -le. I add 1 only when I print the number for humans.

Change array items in place

A foreach loop gives you a copy of each value, so assigning to it doesn’t change the ar