Loops and Iteration

How PowerShell's foreach, ForEach-Object, .ForEach(), for, while and do loops differ, with measured timings, labels, hashtable iteration and retry loops.

By The Dark DebuggerUpdated 30 min read

This article covers every way PowerShell can repeat work: the foreach statement, the ForEach-Object cmdlet, the .ForEach() and .Where() methods, for, while, do, and the break/continue keywords that steer them. It assumes you know the object pipeline, arrays and hashtables and if and switch. After this come functions, where most of these loops end up living.

Why loops deserve a whole article

Most real scripts are a loop with something interesting inside: check every server in a list, summarise every log file in a folder, page through every result of a REST API, retry a flaky call until it works. PowerShell gives you three different ways to write "for each item" alone, and they are not interchangeable. They differ in when items arrive, how fast they run, and what break and continue do. Picking the wrong one gives you a script that works on ten test files and falls over on ten thousand, or one that silently skips the last half of its work.

Every example below was saved as a .ps1 file and run with pwsh -NoProfile -File (PowerShell 7.6.9) in a folder that holds a small logs directory. That is why error messages show a script path and line number; at the interactive prompt you get a shorter one-line form. Here is the data:

Get-ChildItem -Path ./logs | Format-Table -Property Name, Length
Get-Content -Path ./logs/api.log -TotalCount 3
Name        Length
----        ------
api.log      30679
auth.log     13268
billing.log  19921
empty.log        0
worker.log  113941
 
2026-11-09T08:00:08Z INFO api request path=/v1/orders status=200 ms=18
2026-11-09T08:00:13Z INFO api request path=/v1/orders/7731 status=200 ms=60
2026-11-09T08:00:30Z INFO api request path=/v1/customers status=200 ms=70

The foreach statement

The foreach statement is the workhorse. It takes a collection, binds each element to a variable you name, and runs the block once per element:

$logFiles = Get-ChildItem -Path ./logs -Filter *.log
 
foreach ($file in $logFiles) {
    $lineCount = (Get-Content -Path $file.FullName).Count
    '{0,-12} {1,5} lines' -f $file.Name, $lineCount
}
api.log        420 lines
auth.log       180 lines
billing.log    260 lines
empty.log        0 lines
worker.log    1500 lines

Three behaviours are worth knowing before you rely on it:

$nothing = $null
foreach ($item in $nothing) { "never printed" }
 
$single = 'web01'
foreach ($item in $single) { "one item: $item" }
 
foreach ($n in 1..3) { }
"after the loop, `$n is still $n"
one item: web01
after the loop, $n is still 3
  • Looping over $null runs zero times, so a command that found nothing doesn't need a special case.
  • A single value that isn't a collection is treated as a one-item collection. You don't need to wrap it in @() first.
  • The loop variable is an ordinary variable. It keeps the last value after the loop ends, which can surprise you if you reuse the name later.

The important design fact is that foreach evaluates the whole collection first. In foreach ($line in Get-Content big.log), PowerShell reads the entire file into memory, then starts looping. For a 20 MB log that's fine. For a 4 GB log it isn't, and that's where ForEach-Object comes in.

ForEach-Object: looping inside the pipeline

ForEach-Object is a cmdlet that runs a script block for each object coming down the pipeline. The current object is $_ (or its long name $PSItem). It also takes optional -Begin and -End blocks that run once before and after all the objects:

Get-ChildItem -Path ./logs -Filter *.log |
    ForEach-Object -Begin {
        $total = 0
    } -Process {
        $total += $_.Length
        '{0,-12} {1,7:N0} bytes' -f $_.Name, $_.Length
    } -End {
        'Total: {0:N0} bytes' -f $total
    }
api.log       30,679 bytes
auth.log      13,268 bytes
billing.log   19,921 bytes
empty.log          0 bytes
worker.log   113,941 bytes
Total: 177,809 bytes

The real difference from the foreach statement is streaming. This example uses a small function that announces each object as it produces it, so we can see the order of events:

function Get-Record {
    foreach ($id in 1..3) {
        Write-Host "  produced $id"
        [pscustomobject]@{ Id = $id }
    }
}
 
Write-Host 'Pipeline with ForEach-Object:'
Get-Record | ForEach-Object { Write-Host "  consumed $($_.Id)" }
 
Write-Host 'foreach statement:'
foreach ($record in Get-Record) { Write-Host "  consumed $($record.Id)" }
Pipeline with ForEach-Object:
  produced 1
  consumed 1
  produced 2
  consumed 2
  produced 3
  consumed 3
foreach statement:
  produced 1
  produced 2
  produced 3
  consumed 1
  consumed 2
  consumed 3

With the pipeline, each record is handled as soon as it exists, so only one is in memory at a time. With the statement, all three were produced and collected before the first one was consumed. That's the trade-off in one picture. Get-Content huge.log | ForEach-Object { … } runs in roughly constant memory and shows its first result immediately. foreach ($line in Get-Content huge.log) holds the whole file in memory but loops faster.

foreach is also an alias

foreach and % are aliases for ForEach-Object. PowerShell decides by position: at the start of a statement foreach (...) is the loop statement; after a pipe | foreach { } is the cmdlet. In scripts, write ForEach-Object in full so nobody has to work out which one you meant.

The .ForEach() and .Where() methods

Since PowerShell 4, every collection has two "magic" methods that loop over items already in memory without the pipeline's overhead. .ForEach() accepts a script block, a property name, or a type to convert to. .Where() filters, and takes an optional mode as its second argument:

$files = Get-ChildItem -Path ./logs -Filter *.log
 
$files.ForEach('Name')
 
$files.Where({ $_.Length -gt 50KB }).ForEach({
    '{0} is {1:N1} KB' -f $_.Name, ($_.Length / 1KB)
})
 
$files.Where({ $_.Length -eq 0 }, 'First').Name
 
$small, $large = $files.Where({ $_.Length -lt 30KB }, 'Split')
"small: $($small.Name -join ', ')"
"large: $($large.Name -join ', ')"
api.log
auth.log
billing.log
empty.log
worker.log
worker.log is 111.3 KB
empty.log
small: api.log, auth.log, billing.log, empty.log
large: worker.log
.Where() modeReturns
'Default' (or omitted)Every item where the block is true
'First', 'Last'Only the first or last match. Add a count for more: .Where({…}, 'First', 3)
'SkipUntil'Everything from the first match onwards
'Until'Everything before the first match
'Split'Two collections, matches and non-matches, which you can assign to two variables

'First' stops evaluating as soon as it finds a match, which makes it a cheap "find". 'Split' replaces two separate Where-Object passes.

Which one is fastest? Measured

Here is the same work, summing a million integers, done three ways:

$numbers = 1..1000000
 
$timings = [ordered]@{
    'foreach statement' = Measure-Command {
        $sum = 0
        foreach ($n in $numbers) { $sum += $n }
    }
    'ForEach-Object' = Measure-Command {
        $sum = 0
        $numbers | ForEach-Object { $sum += $_ }
    }
    '.ForEach() method' = Measure-Command {
        $sum = 0
        $numbers.ForEach({ $sum += $_ })
    }
}
 
foreach ($entry in $timings.GetEnumerator()) {
    '{0,-18} {1,8:N0} ms' -f $entry.Key, $entry.Value.TotalMilliseconds
}

On PowerShell 7.6.9 (Linux):

foreach statement     3,202 ms
ForEach-Object        6,723 ms
.ForEach() method     3,678 ms

The same script on Windows PowerShell 5.1:

foreach statement     2,331 ms
ForEach-Object       14,383 ms
.ForEach() method     9,364 ms

I ran the 7.6 version five times on a busy test machine. The absolute numbers moved by a factor of two between runs, but the ranking never changed: ForEach-Object was 2 to 3.5 times slower than the foreach statement, and .ForEach() was close to the statement. On 5.1 the gap is far wider, and ForEach-Object was six times slower. PowerShell 7 made the cmdlet much cheaper, so if you maintain 5.1 scripts, tight loops are where 7 pays off first.

Don't over-read these numbers, though. A million trivial iterations cost a few seconds. If each iteration makes a network call or reads a file, the loop mechanics disappear in the noise. Choose by behaviour first and speed second:

UseWhen
foreach ($x in $items)The data is already in memory (a variable, a small file), you want speed, or you need break/continue
… | ForEach-Object { }You're in the middle of a pipeline, the input is large or slow to arrive, or you want results to appear as they're produced
$items.ForEach({ }) / .Where({ })Quick transforms or filters on an in-memory collection, especially .Where(…, 'First') and 'Split'
for ($i = 0; …)You need the index: batching, stepping by more than one, walking backwards, comparing neighbours

The for loop: when you need the index

for has three parts: an initialiser, a condition checked before every iteration, and a step that runs after every iteration. Reach for it when the position matters. A common real case is splitting work into batches, for example rebooting hosts three at a time so the load balancer always has healthy nodes:

$hosts = 'web01', 'web02', 'web03', 'web04', 'web05', 'web06', 'web07'
$batchSize = 3
 
for ($i = 0; $i -lt $hosts.Count; $i += $batchSize) {
    $last  = [math]::Min($i + $batchSize, $hosts.Count) - 1
    $batch = $hosts[$i..$last]
    'Batch {0}: {1}' -f ($i / $batchSize + 1), ($batch -join ', ')
}
Batch 1: web01, web02, web03
Batch 2: web04, web05, web06
Batch 3: web07

The [math]::Min stops the last batch from reading past the end of the array.

The other classic is removing items from a list while you walk it. Go backwards, because removing an item shifts everything after it down by one:

$files = [System.Collections.Generic.List[string]]@(
    'build.tmp', 'cache.tmp', 'report.pdf', 'notes.txt', 'swap.tmp'
)
 
for ($i = $files.Count - 1; $i -ge 0; $i--) {
    if ($files[$i] -like '*.tmp') {
        $files.RemoveAt($i)
    }
}
$files
report.pdf
notes.txt

Run the same loop forwards (for ($i = 0; $i -lt $files.Count; $i++)) and you get this:

cache.tmp
report.pdf
notes.txt

cache.tmp survived. After build.tmp at index 0 was removed, cache.tmp slid into index 0, but the loop had already moved on to index 1. No error, just a wrong answer. That makes it worse than a crash.

while: loop until something changes

while checks its condition before each iteration, so the body may never run. Use it when you don't know how many iterations you need. Draining a work queue is the cleanest example. Here a breadth-first walk of a directory tree adds new work to the queue as it goes:

$queue = [System.Collections.Generic.Queue[string]]::new()
$queue.Enqueue('/srv/app/releases')
$queue.Enqueue('/srv/app/shared')
 
$children = @{
    '/srv/app/releases'            = '/srv/app/releases/2026-11-01', '/srv/app/releases/2026-11-08'
    '/srv/app/releases/2026-11-08' = '/srv/app/releases/2026-11-08/config'
}
 
while ($queue.Count -gt 0) {
    $dir = $queue.Dequeue()
    "visiting $dir"
    foreach ($child in $children[$dir]) {
        $queue.Enqueue($child)
    }
}
visiting /srv/app/releases
visiting /srv/app/shared
visiting /srv/app/releases/2026-11-01
visiting /srv/app/releases/2026-11-08
visiting /srv/app/releases/2026-11-08/config

A foreach can't do this, because it fixes its collection before it starts.

The other everyday while is polling with a timeout: wait for a deploy marker, a lock to be released, or a service to come up, and give up after a deadline. Never write a polling loop without the deadline. "It'll appear eventually" is how scheduled jobs end up hanging for a week.

$flag    = './deploy/ready.flag'
$timeout = [timespan]::FromSeconds(10)
$clock   = [System.Diagnostics.Stopwatch]::StartNew()
 
while (-not (Test-Path -Path $flag)) {
    if ($clock.Elapsed -gt $timeout) {
        throw "Timed out after $($timeout.TotalSeconds)s waiting for $flag"
    }
    Write-Host ('waiting for {0} ({1:N0}s)' -f $flag, $clock.Elapsed.TotalSeconds)
    Start-Sleep -Seconds 1
}
'Found {0} after {1:N1}s' -f $flag, $clock.Elapsed.TotalSeconds

While this ran, a separate process created deploy/ready.flag six seconds after the script was launched:

waiting for ./deploy/ready.flag (1s)
waiting for ./deploy/ready.flag (2s)
waiting for ./deploy/ready.flag (3s)
waiting for ./deploy/ready.flag (4s)
waiting for ./deploy/ready.flag (5s)
Found ./deploy/ready.flag after 6.4s

The first line says 1s, not 0s, because the first Test-Path call in a fresh process took most of a second to load. A Stopwatch measures real elapsed time, so the deadline stays accurate even when the loop body is slow. Counting iterations and assuming each one takes a second does not.

do-while and do-until: run the body at least once

The do loops check their condition after the body, so the body always runs at least once. do { } while (cond) keeps going while the condition is true. do { } until (cond) keeps going until it becomes true. Pick whichever reads more naturally. They are mirror images.

Paging through an API is the textbook do-while: you must make the first request before you know whether there's a second page. The function below stands in for a REST endpoint that returns four users per page plus a token for the next page:

# Stand-in for a paged REST API: 4 items per page plus a token for the next page.
$allUsers = 1..10 | ForEach-Object { 'user{0:D2}' -f $_ }
function Get-UserPage {
    param([int]$Token)
    $next = if ($Token + 4 -lt $allUsers.Count) { $Token + 4 } else { $null }
    [pscustomobject]@{
        Items     = $allUsers | Select-Object -Skip $Token -First 4
        NextToken = $next
    }
}
 
$token = 0
$users = do {
    $response = Get-UserPage -Token $token
    Write-Host "token $token returned $($response.Items.Count) items"
    $response.Items
    $token = $response.NextToken
} while ($null -ne $token)
 
"Collected $($users.Count) users: $($users -join ', ')"
token 0 returned 4 items
token 4 returned 4 items
token 8 returned 2 items
Collected 10 users: user01, user02, user03, user04, user05, user06, user07, user08, user09, user10

Two details matter here. The loop's output is assigned straight to $users, which is the efficient way to collect results (more on that below). And the condition is $null -ne $token, not just $token. A bare while ($token) treats 0 and an empty string as false, and some real APIs use exactly those values as valid tokens.

do-until suits "keep trying candidates until one is free". This finds the next unused report name when daily-report-01.csv and daily-report-02.csv already exist:

$n = 0
do {
    $n++
    $candidate = './reports/daily-report-{0:D2}.csv' -f $n
} until (-not (Test-Path -Path $candidate))
 
"Next free name: $candidate"
Next free name: ./reports/daily-report-03.csv

break, continue, and labels

continue skips the rest of the current iteration. break leaves the loop entirely. Together they make "find the first match" cheap:

foreach ($line in Get-Content -Path ./logs/api.log) {
    if ($line -notmatch ' ERROR ') { continue }
    "First error: $line"
    break
}
First error: 2026-11-09T08:23:05Z ERROR api request path=/healthz status=500 ms=763

With nested loops, a plain break only leaves the innermost loop. To leave an outer loop, put a label (:name) in front of it and pass the name to break or continue. This scans every log for a FATAL line and stops everything at the first one:

$logFiles = Get-ChildItem -Path ./logs -Filter *.log
 
:files foreach ($file in $logFiles) {
    Write-Host "scanning $($file.Name)"
    foreach ($line in Get-Content -Path $file.FullName) {
        if ($line -match ' FATAL ') {
            "FATAL in $($file.Name): $line"
            break files
        }
    }
}
scanning api.log
scanning auth.log
scanning billing.log
FATAL in billing.log: 2026-11-09T09:02:41Z FATAL billing ledger write failed: disk quota exceeded

worker.log was never opened. continue files would instead jump to the next file, which is what you want for "first match per file".

One trap catches nearly everyone once: switch counts as a loop. A break inside a switch only leaves the switch, not the foreach around it:

$events = 'deploy-start', 'health-ok', 'rollback', 'health-ok', 'deploy-end'
 
foreach ($event in $events) {
    switch ($event) {
        'rollback' { 'rollback seen, stopping'; break }
        default    { "processing $event" }
    }
}
'--- with a label:'
:events foreach ($event in $events) {
    switch ($event) {
        'rollback' { 'rollback seen, stopping'; break events }
        default    { "processing $event" }
    }
}
processing deploy-start
processing health-ok
rollback seen, stopping
processing health-ok
processing deploy-end
--- with a label:
processing deploy-start
processing health-ok
rollback seen, stopping

The first loop printed "stopping" and then carried on processing. The label fixes it.

Iterating over hashtables

A hashtable is a single object, so foreach over it runs once, with the whole table as the loop variable. To loop over the entries, call .GetEnumerator(). Each entry has .Key and .Value. Hashtables have no order, so sort the entries if the output order matters:

$ports = @{ api = 8080; auth = 8443; billing = 9000; worker = 9100 }
 
$count = 0
foreach ($entry in $ports) { $count++ }
"Iterations over the hashtable itself: $count"
 
foreach ($entry in $ports.GetEnumerator() | Sort-Object -Property Key) {
    '{0,-8} -> {1}' -f $entry.Key, $entry.Value
}
Iterations over the hashtable itself: 1
api      -> 8080
auth     -> 8443
billing  -> 9000
worker   -> 9100

Looping over $ports.Keys also works, until you try to change the table inside the loop:

$ports = @{ api = 8080; auth = 8443; billing = 9000; worker = 9100 }
 
foreach ($name in $ports.Keys) {
    $ports[$name] += 1000
}
OperationStopped: /home/sid/loops/hashtable-modify.ps1:3
Line |
   3 |  foreach ($name in $ports.Keys) {
     |           ~~~~~
     | Collection was modified; enumeration operation may not execute.

.Keys is a live view of the table, and .NET refuses to keep enumerating a collection that changed underneath it. Even updating an existing value counts as a change. The fix is to loop over a copy of the keys, and @() makes one:

$ports = @{ api = 8080; auth = 8443; billing = 9000; worker = 9100 }
 
foreach ($name in @($ports.Keys)) {
    $ports[$name] += 1000
}
$ports.GetEnumerator() | Sort-Object -Property Value
Name                           Value
----                           -----
api                            9080
auth                           9443
billing                        10000
worker                         10100

The same error and the same fix apply to List[T], ArrayList and dictionaries. Never add to or remove from the collection you're walking. Walk a copy, or use the backwards for loop from earlier.

Building results without +=

This is the most common performance mistake in PowerShell scripts:

$result = @()
foreach ($server in $servers) {
    $result += Get-Something $server
}

PowerShell arrays have a fixed size. += doesn't append. It allocates a new array one element larger and copies everything across, on every iteration. The cost grows with the square of the item count. Compare it with the two alternatives:

$count = 20000
 
$plusEquals = Measure-Command {
    $result = @()
    foreach ($i in 1..$count) { $result += "item $i" }
}
$assigned = Measure-Command {
    $result = foreach ($i in 1..$count) { "item $i" }
}
$list = Measure-Command {
    $result = [System.Collections.Generic.List[string]]::new()
    foreach ($i in 1..$count) { $result.Add("item $i") }
}
 
'{0,-22} {1,8:N0} ms' -f '$result += ...', $plusEquals.TotalMilliseconds
'{0,-22} {1,8:N0} ms' -f '$result = foreach ...', $assigned.TotalMilliseconds
'{0,-22} {1,8:N0} ms' -f 'List[string].Add()', $list.TotalMilliseconds

PowerShell 7.6.9:

$result += ...            2,738 ms
$result = foreach ...        89 ms
List[string].Add()           91 ms

Windows PowerShell 5.1, same script:

$result += ...           21,405 ms
$result = foreach ...        64 ms
List[string].Add()           76 ms

Twenty-one seconds against sixty milliseconds for the same 20,000 strings on 5.1. PowerShell 7 made += much cheaper, but it is still around 30 times slower here, and the gap widens as the count grows.

The idiomatic fix is the middle one: assign the loop itself to a variable. Everything the loop body outputs is collected for you. This works with foreach, for, while, do, switch and ForEach-Object. Use a List[T] when you need to add from several places, or to add conditionally deep inside nested logic.

One catch with assignment: the result's shape depends on how many items came out.

$none = foreach ($f in @()) { $f }
$one  = foreach ($f in 'web01') { $f }
$many = foreach ($f in 'web01', 'web02') { $f }
 
"none: $($null -eq $none)"
"one:  $($one.GetType().Name)"
"many: $($many.GetType().Name)"
 
$safe = @(foreach ($f in 'web01') { $f })
"safe: $($safe.GetType().Name) with Count $($safe.Count)"
none: True
one:  String
many: Object[]
safe: Object[] with Count 1

Zero items gives $null, one item gives the item itself, two or more give an array. If later code indexes into the result or relies on array methods, wrap the loop in @( … ) so you always get an array.

Showing progress with Write-Progress

For loops that take more than a few seconds, Write-Progress draws a progress bar. It doesn't write to the output stream, so it never ends up in a variable or a file:

$files = Get-ChildItem -Path ./logs -Filter *.log
$index = 0
 
foreach ($file in $files) {
    $index++
    Write-Progress -Activity 'Scanning logs' `
        -Status "$index of $($files.Count): $($file.Name)" `
        -PercentComplete ($index / $files.Count * 100)
    Start-Sleep -Milliseconds 400
}
Write-Progress -Activity 'Scanning logs' -Completed
"Scanned $index files"

The only thing the script outputs is:

Scanned 5 files

When I ran it in a terminal, PowerShell 7 drew a single-line bar at the top of the window and redrew it in place for each file. This was the third frame, with the colour codes stripped (the filled part of the bar is shown in reverse video):

Scanning logs [3 of 5: billing.log                                           ]

Windows PowerShell 5.1 draws the older multi-line block instead. In 7 you can get that style back with $PSStyle.Progress.View = 'Classic'. A few practical rules:

  • Always finish with -Completed. Otherwise a stale bar can stay on screen until the script exits.
  • Pass -Id and -ParentId to show a nested bar, for example files inside folders.
  • Set $ProgressPreference = 'SilentlyContinue' in scripts that run unattended. Progress is pointless in a scheduled task. On 5.1, the progress display of Invoke-WebRequest was also notorious for slowing downloads.
  • In loops over tens of thousands of items, update every Nth item (if ($index % 100 -eq 0)) rather than every item.

Retry loops with backoff

Networks fail. A call to an API, a package feed or a database will sometimes fail once and succeed a second later. A retry loop with exponential backoff waits 0.5s, then 1s, then 2s, and so on, so a struggling service gets more breathing room on each attempt. Add a little random jitter so a hundred clients that failed together don't all retry at the same instant. This uses try/catch, which gets its own article in error handling. For now, read it as "if the block throws, run the catch block":

function Invoke-WithRetry {
    param(
        [scriptblock]$Action,
        [int]$MaxAttempts = 4,
        [double]$BaseDelaySeconds = 0.5
    )
 
    for ($attempt = 1; $attempt -le $MaxAttempts; $attempt++) {
        try {
            return & $Action
        }
        catch {
            if ($attempt -eq $MaxAttempts) {
                throw "Giving up after $MaxAttempts attempts: $($_.Exception.Message)"
            }
            $delay  = $BaseDelaySeconds * [math]::Pow(2, $attempt - 1)
            $delay += Get-Random -Minimum 0.0 -Maximum ($delay / 4)
            Write-Warning ('Attempt {0} failed: {1}. Retrying in {2:N2}s' -f
                $attempt, $_.Exception.Message, $delay)
            Start-Sleep -Milliseconds ($delay * 1000)
        }
    }
}
 
# A fake API call that fails twice with HTTP 503, then succeeds.
$state = @{ Calls = 0 }
$inventory = Invoke-WithRetry -Action {
    $state.Calls++
    if ($state.Calls -lt 3) { throw 'HTTP 503 from inventory API' }
    'inventory: 42 hosts'
}
$inventory
 
# One that never recovers.
Invoke-WithRetry -MaxAttempts 3 -Action { throw 'connection refused' }
'not reached'
WARNING: Attempt 1 failed: HTTP 503 from inventory API. Retrying in 0.56s
WARNING: Attempt 2 failed: HTTP 503 from inventory API. Retrying in 1.16s
inventory: 42 hosts
WARNING: Attempt 1 failed: connection refused. Retrying in 0.52s
WARNING: Attempt 2 failed: connection refused. Retrying in 1.15s
Exception: /home/sid/loops/retry.ps1:14
Line |
  14 |  …             throw "Giving up after $MaxAttempts attempts: $($_.Except …
     |                ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     | Giving up after 3 attempts: connection refused

Some details that are easy to get wrong:

  • return & $Action leaves the function on the first success. The for loop only continues when the block throws.
  • After the last attempt, the function rethrows instead of returning nothing. A retry helper that swallows the final failure turns an outage into silently missing data.
  • The fake API keeps its call count in a hashtable ($state.Calls++). The script block runs in its own scope, so $calls++ on a plain variable would increment a temporary copy, and the count would never reach 3. Scopes are covered properly later.
  • Only retry errors that can succeed later: timeouts, HTTP 429/502/503, "connection reset". Retrying a 401 or a "file not found" just delays the inevitable.

Where you'll use this

Loops are the skeleton of almost every operational script:

  • Fleet operations. for with a step to patch or restart servers in batches. foreach over an inventory CSV to collect disk, certificate or service status from each machine.
  • Waiting on systems. while with a stopwatch deadline after a deployment: wait for the health endpoint, the lock file or the replication flag.
  • Paged APIs. do/while over the nextLink or continuation token of cloud and SaaS APIs. Almost every list endpoint pages its results.
  • Resilient automation. Retry loops around anything that crosses a network.
  • Log and report crunching. A loop over files with an inner loop over lines, building objects you can sort, export or email.

Here is that last one complete: a per-service error report across every log in a folder. It skips empty files with continue, uses switch -Regex -File as the inner loop (it reads the file line by line, so memory stays flat even for big logs), and collects one object per file by assigning the loop to $report:

$logFiles = Get-ChildItem -Path ./logs -Filter *.log
 
$report = foreach ($file in $logFiles) {
    if ($file.Length -eq 0) {
        Write-Warning "Skipping empty file $($file.Name)"
        continue
    }
 
    $counts = @{ INFO = 0; WARN = 0; ERROR = 0; FATAL = 0 }
    switch -Regex -File $file.FullName {
        '^\S+ (INFO|WARN|ERROR|FATAL) ' { $counts[$Matches[1]]++ }
    }
 
    $total = $counts.INFO + $counts.WARN + $counts.ERROR + $counts.FATAL
    [pscustomobject]@{
        Service  = $file.BaseName
        Lines    = $total
        Warnings = $counts.WARN
        Errors   = $counts.ERROR + $counts.FATAL
        ErrorPct = [math]::Round(100 * ($counts.ERROR + $counts.FATAL) / $total, 1)
    }
}
 
$report | Sort-Object -Property ErrorPct -Descending | Format-Table -AutoSize
WARNING: Skipping empty file empty.log
 
Service Lines Warnings Errors ErrorPct
------- ----- -------- ------ --------
billing   260        7     18     6.90
api       420       27     10     2.40
auth      180        5      1     0.60
worker   1500       49      6     0.40

Because $report holds objects rather than text, the same loop can feed Export-Csv, a threshold check ($report | Where-Object ErrorPct -gt 5) or an alert email without changes. That's the payoff of building results instead of printing them.

Common mistakes

Using continue or break inside ForEach-Object

This looks like it should skip the empty file and print Done.:

Get-ChildItem -Path ./logs -Filter *.log | ForEach-Object {
    if ($_.Length -eq 0) { continue }
    '{0}: {1:N0} bytes' -f $_.Name, $_.Length
}
'Done.'
api.log: 30,679 bytes
auth.log: 13,268 bytes
billing.log: 19,921 bytes

worker.log is missing, and so is Done.. There is no error. The ForEach-Object script block isn't a loop. continue looks up the call stack for an enclosing loop, finds none, and ends the whole script with a success exit code. Inside a function called from a loop, it would continue that outer loop instead, which is just as surprising.

The fix: inside ForEach-Object, use return to skip to the next object:

Get-ChildItem -Path ./logs -Filter *.log | ForEach-Object {
    if ($_.Length -eq 0) { return }
    '{0}: {1:N0} bytes' -f $_.Name, $_.Length
}
'Done.'
api.log: 30,679 bytes
auth.log: 13,268 bytes
billing.log: 19,921 bytes
worker.log: 113,941 bytes
Done.

If you need a real break, use a foreach statement, or Select-Object -First to stop the pipeline early.

Using $_ in a foreach statement

$_ belongs to the pipeline. The foreach statement sets only the variable you named:

foreach ($file in Get-ChildItem -Path ./logs -Filter *.log) {
    "Name: [$($_.Name)]"
}
Name: []
Name: []
Name: []
Name: []
Name: []

No error, just empty values, because $_ is $null here. Use $file.Name. If you paste a ForEach-Object body into a foreach statement, search it for $_ first.

Changing a collection while you loop over it

Covered above, but it belongs on this list: removing items while looping forwards over a list skips elements silently (cache.tmp survived), and changing a hashtable while enumerating .Keys throws Collection was modified. Loop over a copy (@($h.Keys)) or backwards by index.

Summary

  • The foreach statement loads the whole collection, then loops quickly. ForEach-Object streams one object at a time through the pipeline. .ForEach()/.Where() are fast methods for collections already in memory.
  • Measured on a million items, ForEach-Object was 2 to 3.5 times slower than foreach on PowerShell 7.6 and about 6 times slower on 5.1. Choose by behaviour (streaming, memory, break) before speed.
  • for is for index work: batching with a step, walking backwards to remove items safely, comparing neighbours.
  • while checks first and may run zero times. do/while and do/until run at least once, which suits paging and "try the next candidate".
  • break and continue affect the innermost loop, and switch counts as a loop. Labels (:outer … break outer) reach outer loops. Inside ForEach-Object, use return to skip an item.
  • Loop over a hashtable with .GetEnumerator(), and over @($h.Keys) if you modify it.
  • Collect results by assigning the loop ($r = foreach …), or with a List[T]. Never use += on arrays in a loop. Wrap in @() when you need an array even for one result.
  • Polling and retry loops always need a deadline or a maximum number of attempts, and the final failure must be rethrown, not swallowed.

Exercises

Exercise 1: Restart in batcheseasy

Generate ten host names app01 to app10 and print them in batches of four, one batch per line, with a batch number. The last batch has only two hosts and must not show empty entries.

Show Solution
$hosts = 1..10 | ForEach-Object { 'app{0:D2}' -f $_ }
 
for ($i = 0; $i -lt $hosts.Count; $i += 4) {
    $last = [math]::Min($i + 4, $hosts.Count) - 1
    'Batch {0}: {1}' -f ($i / 4 + 1), ($hosts[$i..$last] -join ' ')
}
Batch 1: app01 app02 app03 app04
Batch 2: app05 app06 app07 app08
Batch 3: app09 app10

The step $i += 4 moves a whole batch at a time. [math]::Min clamps the end index for the final, short batch.

Exercise 2: Sort and shift a port mapeasy

Start from $ports = @{ api = 8080; auth = 8443; billing = 9000; worker = 9100 }. Print each entry as name: port, highest port first. Then add 1000 to every port without getting the "Collection was modified" error, and print the new value for api.

Show Solution
$ports = @{ api = 8080; auth = 8443; billing = 9000; worker = 9100 }
 
foreach ($entry in $ports.GetEnumerator() | Sort-Object -Property Value -Descending) {
    '{0}: {1}' -f $entry.Key, $entry.Value
}
 
foreach ($name in @($ports.Keys)) {
    $ports[$name] += 1000
}
"api is now on $($ports.api)"
worker: 9100
billing: 9000
auth: 8443
api: 8080
api is now on 9080

.GetEnumerator() turns the table into entries that Sort-Object can sort by Value. @($ports.Keys) snapshots the keys so the loop can safely write to the table.

Exercise 3: First error per filemedium

For every .log file in ./logs, print the file name and the timestamp of its first ERROR line, then move straight on to the next file without reading the rest of the current one. Files with no errors should print no errors. Use a labelled continue.

Hint

Put a label on the outer foreach. A continue <label> inside the inner loop skips both the rest of the lines and the "no errors" line after the inner loop.

Show Solution
:file foreach ($file in Get-ChildItem -Path ./logs -Filter *.log) {
    foreach ($line in Get-Content -Path $file.FullName) {
        if ($line -match ' ERROR ') {
            '{0,-12} {1}' -f $file.Name, $line.Substring(0, 20)
            continue file
        }
    }
    '{0,-12} no errors' -f $file.Name
}
api.log      2026-11-09T08:23:05Z
auth.log     2026-11-09T08:28:57Z
billing.log  2026-11-09T08:00:27Z
empty.log    no errors
worker.log   2026-11-09T08:23:05Z

continue file jumps to the next iteration of the outer loop, so the no errors line only runs when the inner loop finishes without a match.

Exercise 4: Count HTTP status codesmedium

Every request line in the logs contains status=NNN. Count how many times each status code appears across all the log files, and print the codes in ascending order with their counts. Read each file line by line rather than loading it whole.

Show Solution
$statusCounts = @{}
 
foreach ($file in Get-ChildItem -Path ./logs -Filter *.log) {
    switch -Regex -File $file.FullName {
        'status=(\d{3})' { $statusCounts[$Matches[1]] += 1 }
    }
}
 
foreach ($status in $statusCounts.Keys | Sort-Object) {
    '{0}  {1,5}' -f $status, $statusCounts[$status]
}
200   2325
500     20
503     14

switch -File is a loop over the file's lines, and $Matches[1] holds the captured code. $statusCounts[$code] += 1 works even for a code not seen before, because a missing key reads as $null and $null + 1 is 1.

Exercise 5: Retry with a capped backoffhard

Write Invoke-WithRetry using a do/until loop instead of for. It should take -Action, -MaxAttempts (default 5), -BaseDelaySeconds (default 0.25) and -MaxDelaySeconds (default 1). The delay doubles after each failure but never exceeds the cap. It must rethrow the last error when attempts run out. Test it with an action that fails four times and succeeds on the fifth call.

Show Solution
function Invoke-WithRetry {
    param(
        [scriptblock]$Action,
        [int]$MaxAttempts = 5,
        [double]$BaseDelaySeconds = 0.25,
        [double]$MaxDelaySeconds = 1
    )
 
    $attempt = 0
    $succeeded = $false
    do {
        $attempt++
        try {
            $result = & $Action
            $succeeded = $true
        }
        catch {
            if ($attempt -ge $MaxAttempts) { throw }
            $delay = [math]::Min($BaseDelaySeconds * [math]::Pow(2, $attempt - 1), $MaxDelaySeconds)
            Write-Host ('attempt {0} failed ({1}); sleeping {2}s' -f $attempt, $_.Exception.Message, $delay)
            Start-Sleep -Milliseconds ($delay * 1000)
        }
    } until ($succeeded)
 
    $result
}
 
$state = @{ Calls = 0 }
Invoke-WithRetry -Action {
    $state.Calls++
    if ($state.Calls -lt 5) { throw "timeout #$($state.Calls)" }
    "succeeded on call $($state.Calls)"
}
attempt 1 failed (timeout #1); sleeping 0.25s
attempt 2 failed (timeout #2); sleeping 0.5s
attempt 3 failed (timeout #3); sleeping 1s
attempt 4 failed (timeout #4); sleeping 1s
succeeded on call 5

The cap shows on attempts 3 and 4: the uncapped delay would have been 1s and then 2s. A bare throw inside catch rethrows the original error with its details intact. Change the test to fail six times and you'll see timeout #5 surface as the final error.


Tested with: PowerShell 7.6.9 on Ubuntu 24.04 (WSL2) and Windows PowerShell 5.1 on Windows 11, November 2026. Every script was run as shown with pwsh -NoProfile -File. The 5.1 runs were the two timing scripts, which only compute in memory. Timings varied by up to a factor of two between runs on the busy test machine; the rankings did not. The progress bar frame was captured by running the script under a pseudo-terminal and stripping the escape codes. Paths from the test machine's scratch directories are shown shortened to /home/sid/….

Was this page helpful?
The Dark Debugger

Written by The Dark Debugger

Engineer documenting the things that took me too long to learn, so they take you less time. Every PowerShell tutorial here is tested end to end before publishing.