Bird
0
0

Which of the following is the correct syntax to use ForEach-Object to print each item in a list?

easy📝 Syntax Q12 of 15
PowerShell - Cmdlets and Pipeline
Which of the following is the correct syntax to use ForEach-Object to print each item in a list?
A1..3 | ForEach-Object { Write-Output $_ }
BForEach-Object 1..3 { Write-Output $_ }
CWrite-Output 1..3 | ForEach-Object $_
D1..3 ForEach-Object { $_ }
Step-by-Step Solution
Solution:
  1. Step 1: Identify correct pipeline usage

    In PowerShell, ForEach-Object is used after a pipeline to process each item, so the syntax is: collection | ForEach-Object { script }
  2. Step 2: Check the script block and variable usage

    The script block uses $_ to refer to the current item. 1..3 | ForEach-Object { Write-Output $_ } correctly uses this syntax.
  3. Final Answer:

    1..3 | ForEach-Object { Write-Output $_ } -> Option A
  4. Quick Check:

    Pipeline + ForEach-Object + { $_ } = correct syntax [OK]
Quick Trick: Use pipeline before ForEach-Object and $_ inside braces [OK]
Common Mistakes:
  • Placing ForEach-Object before the collection
  • Not using curly braces for the script block
  • Using $_ outside the script block

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More PowerShell Quizzes