0
0
PowerShellscripting~10 mins

For loop in PowerShell - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - For loop
Initialize i=0
Check: i -lt 5?
NoEXIT
Yes
Execute body
Update: i = i + 1
Back to Check
The loop starts by setting i to 0, then checks if i is less than 5. If yes, it runs the loop body, then increases i by 1 and repeats. If no, it stops.
Execution Sample
PowerShell
for ($i = 0; $i -lt 5; $i++) {
    Write-Output $i
}
This loop prints numbers from 0 to 4, increasing i by 1 each time until i is no longer less than 5.
Execution Table
IterationiCondition ($i -lt 5)ActionOutput
10TruePrint 0, i++0
21TruePrint 1, i++1
32TruePrint 2, i++2
43TruePrint 3, i++3
54TruePrint 4, i++4
65FalseExit loop
💡 i reaches 5, condition 5 -lt 5 is False, loop stops
Variable Tracker
VariableStartAfter 1After 2After 3After 4After 5Final
i0123455
Key Moments - 3 Insights
Why does the loop stop when i equals 5?
Because the condition $i -lt 5 becomes False at i=5, as shown in execution_table row 6, so the loop exits.
Does the loop print the number 5?
No, the loop prints numbers only when the condition is True. At i=5, condition is False (row 6), so it does not print 5.
What happens to i after each loop iteration?
i increases by 1 after each iteration, as shown in variable_tracker from 0 up to 5.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the value of i during iteration 3?
A2
B3
C1
D0
💡 Hint
Check the 'i' column in execution_table row for iteration 3.
At which iteration does the loop condition become false?
A5
B6
C4
D1
💡 Hint
Look at the 'Condition' column in execution_table where it changes to False.
If we change the condition to $i -le 5, how many times will the loop run?
A5 times
B4 times
C6 times
D7 times
💡 Hint
Think about when $i -le 5 is True, and check variable_tracker for i values.
Concept Snapshot
For loop syntax in PowerShell:
for (<init>; <condition>; <update>) {
  <body>
}
Loop runs while condition is True.
Update runs after each iteration.
Stops when condition is False.
Full Transcript
This PowerShell for loop example starts with i=0. It checks if i is less than 5. If yes, it prints i and then increases i by 1. This repeats until i reaches 5, when the condition becomes false and the loop stops. The output is numbers 0 to 4 printed one by one. The variable i changes from 0 up to 5, increasing by 1 each time. The loop never prints 5 because the condition fails at that point.