0
0
PowerShellscripting~10 mins

ForEach-Object for iteration in PowerShell - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - ForEach-Object for iteration
Input Collection
ForEach-Object Start
Take One Item
Run ScriptBlock on Item
Output Result
More Items?
YesTake One Item
No
End
ForEach-Object takes each item from a collection, runs a block of code on it, outputs the result, and repeats until all items are processed.
Execution Sample
PowerShell
1..3 | ForEach-Object { $_ * 2 }
This code takes numbers 1 to 3, doubles each, and outputs the results.
Execution Table
StepInput Item ($_)ActionOutput
11Multiply by 22
22Multiply by 24
33Multiply by 26
4No more itemsStop iterationEnd
💡 All items processed, ForEach-Object ends.
Variable Tracker
VariableStartAfter 1After 2After 3Final
$_null123null
Key Moments - 2 Insights
Why does $_ change each step?
Because $_ represents the current item in the pipeline, it updates to the next item each iteration as shown in execution_table rows 1 to 3.
What happens when there are no more items?
The loop stops as shown in execution_table row 4, because ForEach-Object has processed all input items.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output when $_ is 2?
A4
B6
C2
D8
💡 Hint
Check execution_table row 2 where Input Item is 2 and Output is shown.
At which step does the iteration stop?
AStep 3
BStep 4
CStep 2
DStep 1
💡 Hint
Look at execution_table row 4 where it says 'No more items' and 'Stop iteration'.
If the input was 1..4 instead of 1..3, how many output rows would appear before stopping?
A3
B5
C4
D2
💡 Hint
Refer to variable_tracker and execution_table pattern for number of items processed.
Concept Snapshot
ForEach-Object iterates over each item in a collection.
Use $_ to access the current item.
Run a script block on each item.
Outputs the result for each.
Stops when no items remain.
Full Transcript
ForEach-Object in PowerShell takes each item from a collection one by one. It stores the current item in the special variable $_. Then it runs the code inside the script block on that item. The result is output. This repeats until all items are processed. For example, 1..3 | ForEach-Object { $_ * 2 } doubles each number from 1 to 3, outputting 2, 4, and 6. The variable $_ changes each step to the next item. When no items remain, the iteration stops.