Coding

PowerShell For Loop: Syntax, foreach and Examples

A PowerShell for loop has three parts in parentheses, an initializer, a condition and a repeat step, followed by a block in braces: for ($i = 0; $i -lt 5; $i++) { $i }. To visit every item in a collection without managing an index, use foreach ($item in $collection) { ... } instead.

Both are language statements that work in Windows PowerShell 5.1 and in PowerShell 7. The sections below cover the syntax of each, counting and stepping, looping over files, leaving a loop early, and the pipeline cousin ForEach-Object.

PowerShell for loop syntax

The statement looks like this, as shown in Microsoft's about_For page:

for (<Init>; <Condition>; <Repeat>)
{
    <Statement list>
}

Init runs once before the loop starts and usually creates the counter. Condition is tested before every pass. While it evaluates to $true, the block runs. When it becomes $false, the loop ends. Repeat runs after each pass and usually changes the counter. A minimal working example:

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

Example output:

Pass 1
Pass 2
Pass 3
Pass 4
Pass 5

PowerShell uses word operators for comparison, so the test is $i -le 5 (less than or equal), not $i <= 5. The common ones are -lt, -le, -gt, -ge, -eq and -ne. The $i++ in the repeat step adds 1 to $i.

Count up, count down and step by more than one

Because the repeat step is an ordinary expression, you choose the step. The documentation's own example counts in twos:

for ($i = 0; $i -le 20; $i += 2) {
    Write-Host $i
}

That prints 0, 2, 4 and so on up to 20. To count down, start high, test with -ge or -gt, and use $i--:

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

Example output is 3, then 2, then 1. If you get the direction wrong, for instance $i-- with a condition of $i -lt 10, the condition never becomes false and the loop runs until you press Ctrl+C.

Use a for loop to walk an array by index

Reach for for when you need the position as well as the value, or when you want to touch only some positions. Arrays count from 0, and .Count gives the number of items, so the last valid index is .Count - 1. That is why the condition is -lt and not -le:

$names = 'ada', 'grace', 'linus'
for ($i = 0; $i -lt $names.Count; $i++) {
    "{0}: {1}" -f $i, $names[$i]
}

Example output:

0: ada
1: grace
2: linus

Using -le here would read one index past the end of the array. Microsoft's own worked example for for uses the same pattern, $i -lt $fileList.Count, to loop over a list of files by index and rename them.

Two counters, or an endless loop

The initializer and the repeat step can each hold more than one assignment. Microsoft documents this form, with comma-separated expressions:

for (($i = 0), ($j = 10); $i -lt $j; $i++, $j--) {
    "i=$i j=$j"
}

The documentation notes that operations other than pre- or post-increment may not work with every one of the supported syntaxes, so keep multi-counter loops simple. For several conditions, join them with -and or -or in the middle part.

All three parts are optional. for (;;) { ... } loops forever, which is useful for a monitor that you stop with Ctrl+C or with break.

PowerShell foreach loop

The foreach statement hands you each item in turn, with no index to maintain. Its syntax is foreach ($item in $collection) { ... }. PowerShell creates the item variable for you when the loop runs.

$letters = 'a', 'b', 'c', 'd'
foreach ($letter in $letters) {
    Write-Host $letter
}

The collection can also come straight from a cmdlet. This lists files larger than 100 KB in the current folder, adapted from Microsoft's about_Foreach page:

foreach ($file in Get-ChildItem) {
    if ($file.Length -gt 100KB) {
        Write-Host $file.Name ($file.Length / 1KB).ToString('F0') 'KB'
    }
}

100KB and 1KB are built-in size suffixes, so there is no need to type 102400 or 1024. ToString('F0') formats the number with no decimal places. Each $file is a full file object, so any property such as .Name, .Length or .LastWriteTime is available.

Inside a foreach statement, PowerShell also exposes an enumerator in the automatic variable $foreach, with MoveNext() and Current. The documentation uses it to skip ahead inside a loop. You rarely need it.

for or foreach: which one to use

You want toUse
Visit every item in an array or command resultforeach ($x in $items)
Know the index, or step by 2, 5 or backwardsfor ($i = 0; ...; ...)
Repeat something a fixed number of timesfor ($i = 0; $i -lt 10; $i++)
Process objects as they arrive from a pipelineForEach-Object
Run slow, independent work on several items at once (PowerShell 7+)ForEach-Object -Parallel

Microsoft's guidance for for is that a typical use is iterating an array to work on a subset of its values, and that if you want every value, you should consider foreach.

ForEach-Object in a pipeline

ForEach-Object is a cmdlet, not a statement. It reads objects from the pipeline, and inside its script block the current object is $_:

30000, 56798, 12432 | ForEach-Object { $_ / 1024 }

Example output, taken from the cmdlet's documentation:

29.296875
55.466796875
12.140625

It has the aliases foreach and %, so Get-Process | % ProcessName works at a prompt. The docs state it works much like the foreach statement, except that you cannot pipe input into a foreach statement. The cmdlet also has -Begin and -End blocks that run once, before and after all the items.

In PowerShell 7.0 and later, -Parallel runs the script block for several items at once. -ThrottleLimit sets how many run together, with a default of 5. Pass outside variables in with the $Using: prefix:

$prefix = 'Item'
1..8 | ForEach-Object -Parallel { "$Using:prefix $_" } -ThrottleLimit 4

Microsoft warns that each iteration uses a runspace, which adds overhead, so parallel runs can be slower than a normal loop when the work per item is small. Output order is not guaranteed.

Leave a loop early with break, skip with continue

break exits the loop immediately and execution continues after it. This example, from the documentation, finds the index of 30:

$i = 0
$values = 10, 20, 30, 40
foreach ($value in $values) {
    if ($value -eq 30) { break }
    $i++
}
Write-Host "30 was found in array index $i"

continue ends the current pass and moves on to the next one. In a for loop, execution resumes at the repeat step and then the condition, so the counter still advances:

for ($i = 0; $i -lt 10; $i++) {
    if ($i -eq 5) { continue }
    Write-Host $i
}

That prints 0 to 9 and skips 5. To get out of nested loops in one step, put a label in front of the outer loop and name it in the break:

:outer foreach ($row in 1..3) {
    foreach ($col in 1..3) {
        if ($row * $col -eq 4) { break outer }
        "$row x $col"
    }
}

A warning from the Microsoft docs: do not use break or continue inside a ForEach-Object script block. Because that block is not a loop statement, PowerShell looks up the call stack for an enclosing loop, and if it finds none it can end the whole runspace, not just the pipeline. If you need to stop early from a pipeline, use a foreach statement instead, or Select-Object -First to limit the input.

If your loop does not behave

  • It never stops. Check that the repeat step moves the counter toward the condition. Press Ctrl+C to interrupt.
  • It runs one time too many or too few. Compare -lt with -le, and remember arrays start at index 0.
  • Output prints on screen but cannot be captured. Write-Host writes to the host, not to the output stream. Emit the value directly (just $i on its own line) when you want to assign the loop's results to a variable.
  • A script file will not run at all. That is an execution policy question, covered in how to run a .ps1 PowerShell script.

New to the shell itself? PowerShell basic commands covers the cmdlets you will put inside these loops. If you also write Bash, the same ideas are in Bash for loop examples.

Frequently asked questions

What is the difference between for and foreach in PowerShell?
A for loop counts with an initializer, a condition and a repeat step, so you control the index and the step size. A foreach statement takes each item of a collection in turn and gives it to you in a variable. Microsoft's documentation suggests foreach when you want to visit every value in an array, and for when you need to step through values by a pattern.
How do I make an infinite for loop in PowerShell?
Leave all three parts empty: for (;;) { ... }. The loop runs until you press Ctrl+C or a break statement inside the block runs. Use a condition in the middle part instead if you can, so the loop ends by itself.
Is foreach the same as ForEach-Object?
No. foreach used at the start of a statement is a language keyword that loops over a collection already in memory. ForEach-Object is a cmdlet that processes objects arriving from the pipeline, and foreach is also one of its aliases when it appears after a pipe. You cannot pipe input into the foreach statement.
Can I run PowerShell loop iterations in parallel?
Yes, in PowerShell 7 and later: pipe into ForEach-Object -Parallel { ... } and set -ThrottleLimit, which defaults to 5. Windows PowerShell 5.1 does not have this parameter. Each iteration runs in a runspace, so it only pays off when the work per item is large compared with that overhead.

Sources