PowerShell For Loop
A loop runs a block of code repeatedly. The for loop is a counter-controlled loop — it runs a specific number of times based on a start value, a condition, and a step. Use the for loop when the exact number of iterations is known in advance.
How the for Loop Works
for (initializer; condition; iterator) {
# Code block runs on each iteration
}
Step 1: Run initializer → $i = 0
Step 2: Check condition → $i -lt 5 → True? Run body. False? Stop.
Step 3: Run body block
Step 4: Run iterator → $i++
Step 5: Go back to Step 2
Basic for Loop
for ($i = 1; $i -le 5; $i++) {
Write-Host "Count: $i"
}
Output:
Count: 1
Count: 2
Count: 3
Count: 4
Count: 5
Breaking Down Each Part
| Part | Code | Meaning |
|---|---|---|
| Initializer | $i = 1 | Set the counter to 1 before the loop starts |
| Condition | $i -le 5 | Keep looping while $i is less than or equal to 5 |
| Iterator | $i++ | Add 1 to $i after each iteration |
Counting Downward
for ($i = 5; $i -ge 1; $i--) {
Write-Host "Countdown: $i"
}
Write-Host "Launch!"
Output:
Countdown: 5
Countdown: 4
Countdown: 3
Countdown: 2
Countdown: 1
Launch!
Custom Step Size
# Step by 2 (only even numbers)
for ($i = 0; $i -le 10; $i += 2) {
Write-Host "Even: $i"
}
Output:
Even: 0
Even: 2
Even: 4
Even: 6
Even: 8
Even: 10
Looping Through an Array with Index
$servers = @("Web01", "DB01", "Cache01", "Mail01")
for ($i = 0; $i -lt $servers.Count; $i++) {
Write-Host "Server $($i + 1): $($servers[$i])"
}
Output:
Server 1: Web01
Server 2: DB01
Server 3: Cache01
Server 4: Mail01
Nested for Loops
A nested loop places one loop inside another. The inner loop completes all its iterations for each single iteration of the outer loop.
# Print a multiplication table
for ($row = 1; $row -le 3; $row++) {
for ($col = 1; $col -le 3; $col++) {
$product = $row * $col
Write-Host "$row x $col = $product"
}
Write-Host "---"
}
Output:
1 x 1 = 1
1 x 2 = 2
1 x 3 = 3
---
2 x 1 = 2
2 x 2 = 4
2 x 3 = 6
---
3 x 1 = 3
3 x 2 = 6
3 x 3 = 9
---
The break Statement
The break keyword exits the loop immediately, even if the condition is still true.
for ($i = 1; $i -le 10; $i++) {
if ($i -eq 6) {
Write-Host "Stopping at $i"
break
}
Write-Host "Number: $i"
}
Output:
Number: 1
Number: 2
Number: 3
Number: 4
Number: 5
Stopping at 6
The continue Statement
The continue keyword skips the current iteration and moves immediately to the next one.
# Skip odd numbers – print only even numbers
for ($i = 1; $i -le 10; $i++) {
if ($i % 2 -ne 0) {
continue # Skip odd numbers
}
Write-Host "Even: $i"
}
Output:
Even: 2
Even: 4
Even: 6
Even: 8
Even: 10
Real-World Example – File Naming with a Counter
$basePath = "C:\Reports"
for ($month = 1; $month -le 12; $month++) {
$monthName = (Get-Date -Month $month -Day 1).ToString("MMMM")
$fileName = "$basePath\Report_$monthName`_2026.txt"
Write-Host "Creating: $fileName"
# New-Item -Path $fileName -ItemType File -Force
}
Output:
Creating: C:\Reports\Report_January_2026.txt
Creating: C:\Reports\Report_February_2026.txt
Creating: C:\Reports\Report_March_2026.txt
...
Creating: C:\Reports\Report_December_2026.txt
Real-World Example – Retry Logic
$maxRetries = 3
$success = $false
for ($attempt = 1; $attempt -le $maxRetries; $attempt++) {
Write-Host "Attempt $attempt of $maxRetries..."
# Simulated connection test
$connected = $false # Change to $true to simulate success
if ($connected) {
Write-Host "Connected successfully!"
$success = $true
break
} else {
Write-Host "Connection failed."
}
}
if (-not $success) {
Write-Host "All $maxRetries attempts failed. Check the network."
}
Output:
Attempt 1 of 3...
Connection failed.
Attempt 2 of 3...
Connection failed.
Attempt 3 of 3...
Connection failed.
All 3 attempts failed. Check the network.
for vs foreach – When to Use Each
| Use for when... | Use foreach when... |
|---|---|
| The number of iterations is fixed and known | Iterating over all items in a collection |
| The index position is needed | No index is needed — just the value |
| Custom stepping (by 2, 5, 10…) | Simply processing each item in a list |
| Counting up or down | Working with arrays, files, or pipeline output |
Summary
The for loop runs code a set number of times using an initializer, a condition, and an iterator. It handles counting sequences, index-based array access, nested iterations, and retry logic. The break keyword exits early. The continue keyword skips the current iteration. For scenarios where every item in a list needs processing — and the index does not matter — the foreach loop is a better fit.
