Bird
0
0

You want to create a list of squares of numbers from 1 to 5 using ForEach-Object. Which command achieves this and outputs the results?

hard📝 Application Q8 of 15
PowerShell - Cmdlets and Pipeline
You want to create a list of squares of numbers from 1 to 5 using ForEach-Object. Which command achieves this and outputs the results?
A1..5 | ForEach-Object { $_ * $_ }
B1..5 | ForEach-Object { $square = $_ * $_ }
C1..5 | ForEach-Object { Write-Output $_ * $_ }
D1..5 | ForEach-Object { exit $_ * $_ }
Step-by-Step Solution
Solution:
  1. Step 1: Understand output behavior

    Expressions inside the script block output their result automatically.
  2. Step 2: Evaluate each option

    1..5 | ForEach-Object { $_ * $_ }: 1..5 | ForEach-Object { $_ * $_ } outputs squares directly. 1..5 | ForEach-Object { $square = $_ * $_ } only assigns without output. 1..5 | ForEach-Object { Write-Output $_ * $_ } has syntax error due to missing parentheses around $_ * $_. 1..5 | ForEach-Object { exit $_ * $_ } uses exit which terminates PowerShell after first item.
  3. Final Answer:

    1..5 | ForEach-Object { $_ * $_ } -> Option A
  4. Quick Check:

    Direct expression outputs results in ForEach-Object [OK]
Quick Trick: Use direct expressions inside ForEach-Object to output results [OK]
Common Mistakes:
  • Assigning without output
  • Using return inside script block incorrectly
  • Overusing Write-Output unnecessarily

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes