0
0
PowerShellscripting~5 mins

ForEach-Object for iteration in PowerShell - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
What does the <code>ForEach-Object</code> cmdlet do in PowerShell?
It processes each item in a collection one at a time, allowing you to run a script block on each item.
Click to reveal answer
beginner
How do you access the current item inside the ForEach-Object script block?
Use the automatic variable $_ to refer to the current object being processed.
Click to reveal answer
beginner
Example: What will this command output?<br>
1..3 | ForEach-Object { $_ * 2 }
It outputs:<br>2<br>4<br>6<br>Each number from 1 to 3 is multiplied by 2.
Click to reveal answer
intermediate
Can ForEach-Object be used to perform actions other than outputting values? Give an example.
Yes, it can run any code for each item, like writing to a file or calling a function.<br>Example:<br>
1..3 | ForEach-Object { Write-Host "Number: $_" }
Click to reveal answer
intermediate
What is the difference between ForEach-Object and the foreach keyword in PowerShell?
ForEach-Object works with pipeline input and processes items one by one as they come.<br>foreach is a loop that works on a collection already in memory.<br>Use ForEach-Object for streaming data, foreach for looping over arrays.
Click to reveal answer
What variable holds the current item inside a ForEach-Object script block?
A$item
B$_
C$this
D$current
Which of these commands doubles each number from 1 to 5 using ForEach-Object?
AForEach-Object 1..5 { $_ * 2 }
BForEach-Object { 1..5 * 2 }
C1..5 | ForEach-Object { $_ * 2 }
D1..5 | ForEach-Object { 2 }
What is the main use of ForEach-Object in PowerShell?
ATo create functions
BTo declare variables
CTo stop script execution
DTo process each item in a pipeline one by one
Which statement is true about ForEach-Object?
AIt processes items as they come through the pipeline
BIt only works with arrays stored in variables
CIt cannot modify items
DIt is used to define functions
How would you print each item from a list using ForEach-Object?
A1..3 | ForEach-Object { Write-Host $_ }
BWrite-Host 1..3
CForEach-Object { Write-Host $_ } 1..3
DWrite-Host ForEach-Object 1..3
Explain how ForEach-Object works in PowerShell and how you use it to process items.
Think about how you handle each item one by one as it flows through the pipeline.
You got /4 concepts.
    Describe the difference between ForEach-Object and the foreach loop in PowerShell.
    One works with pipeline data, the other with collections already loaded.
    You got /3 concepts.