0
0
PowershellHow-ToBeginner · 3 min read

How to Use For Loop in PowerShell: Syntax and Examples

In PowerShell, use a for loop to repeat commands a set number of times by specifying an initializer, condition, and iterator inside parentheses. The loop runs while the condition is true, executing the code block inside { } each time.
📐

Syntax

The for loop syntax in PowerShell has three parts inside parentheses separated by semicolons:

  • Initializer: Sets the starting value of the loop variable.
  • Condition: The loop runs while this is true.
  • Iterator: Updates the loop variable each time.

The code to repeat goes inside curly braces { }.

powershell
for (<initializer>; <condition>; <iterator>) {
    # commands to repeat
}
💻

Example

This example prints numbers 1 to 5 using a for loop. It shows how the loop variable $i starts at 1, runs while less than or equal to 5, and increases by 1 each time.

powershell
for ($i = 1; $i -le 5; $i++) {
    Write-Output "Number: $i"
}
Output
Number: 1 Number: 2 Number: 3 Number: 4 Number: 5
⚠️

Common Pitfalls

Common mistakes include:

  • Forgetting to update the loop variable, causing an infinite loop.
  • Using incorrect comparison operators like == instead of PowerShell's -eq or -le.
  • Placing the loop code outside the curly braces.

Here is a wrong and right example:

powershell
# Wrong: Infinite loop because iterator missing
for ($i = 1; $i -le 3;) {
    Write-Output $i
}

# Right: Iterator included
for ($i = 1; $i -le 3; $i++) {
    Write-Output $i
}
Output
1 2 3
📊

Quick Reference

PartDescriptionExample
InitializerSets start value$i = 0
ConditionLoop runs while true$i -lt 10
IteratorChanges variable each loop$i++ or $i += 2
Loop BodyCommands to repeatWrite-Output $i

Key Takeaways

Use for loops to repeat commands with a clear start, condition, and update.
Always update the loop variable to avoid infinite loops.
Use PowerShell comparison operators like -le and -lt inside the condition.
Put the repeated commands inside curly braces { }.
Test loops with small ranges to ensure they work as expected.