0
0
PowerShellscripting~20 mins

ForEach-Object for iteration in PowerShell - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
ForEach-Object Master
Get all challenges correct to earn this badge!
Test your skills under time pressure!
💻 Command Output
intermediate
2:00remaining
Output of ForEach-Object with simple arithmetic
What is the output of this PowerShell command?
1..5 | ForEach-Object { $_ * 2 }
PowerShell
1..5 | ForEach-Object { $_ * 2 }
A1 2 3 4 5
B2 4 6 8 10
C0 2 4 6 8
DError: Unexpected token
Attempts:
2 left
💡 Hint
Remember $_ represents the current item in the pipeline.
💻 Command Output
intermediate
2:00remaining
ForEach-Object with conditional output
What does this PowerShell command output?
1..4 | ForEach-Object { if ($_ % 2 -eq 0) { $_ } }
PowerShell
1..4 | ForEach-Object { if ($_ % 2 -eq 0) { $_ } }
A1 2 3 4
B1 3
C2 4
DError: Missing else block
Attempts:
2 left
💡 Hint
Only even numbers are output because of the condition.
📝 Syntax
advanced
2:00remaining
Identify the syntax error in ForEach-Object usage
Which option contains a syntax error in using ForEach-Object?
A1..3 | ForEach-Object Write-Output $_
B1..3 | ForEach-Object { $_ * 3 }
C1..3 | ForEach-Object { Write-Output $_ }
D1..3 | ForEach-Object { $_ + 1 }
Attempts:
2 left
💡 Hint
ForEach-Object requires a script block enclosed in braces {}.
🔧 Debug
advanced
2:00remaining
Why does this ForEach-Object command output only 4 and 5?
Given this command:
1..5 | ForEach-Object { if ($_ -gt 3) { $_ } }

Why does it output only 4 and 5, but not 1, 2, 3?
PowerShell
1..5 | ForEach-Object { if ($_ -gt 3) { $_ } }
ABecause the if condition filters out numbers not greater than 3
BBecause ForEach-Object only processes numbers greater than 3 by default
CBecause the pipeline stops after first two numbers
DBecause $_ is not defined inside the script block
Attempts:
2 left
💡 Hint
Check the condition inside the if statement.
🚀 Application
expert
3:00remaining
Using ForEach-Object to modify and output a list
You have a list of filenames: 'file1.txt', 'file2.txt', 'file3.txt'.
Which command outputs the filenames without the '.txt' extension?
A@('file1.txt','file2.txt','file3.txt') | ForEach-Object { $_.Remove('.txt') }
B@('file1.txt','file2.txt','file3.txt') | ForEach-Object { $_.Replace('.txt','') }
C@('file1.txt','file2.txt','file3.txt') | ForEach-Object { $_ -replace '.txt', '' }
D@('file1.txt','file2.txt','file3.txt') | ForEach-Object { $_ -replace '\.txt$', '' }
Attempts:
2 left
💡 Hint
Use regex to remove only the '.txt' at the end of the string.