In PowerShell, which command applies a command to each object in a pipeline and requires a script block?

Study for the SANS560 GIAC Penetration Tester (GPEN) Test. Study with flashcards and multiple choice questions, each question has hints and explanations. Get ready for your exam!

Multiple Choice

In PowerShell, which command applies a command to each object in a pipeline and requires a script block?

Explanation:
When you want to do something to every object that flows through a PowerShell pipeline, you need a command that runs a script block for each input item. This is exactly what the per-item processor does. ForEach-Object is designed for this role. It takes each object from the pipeline and executes the script block you provide, with the current object accessible inside the block as $_. This lets you transform, filter, or perform actions on every item as it passes through the pipeline. The shorthand alias for this is the percent sign, which is just a quicker way to write it. For example, Get-Service | ForEach-Object { $_.Name } would print the name of each service. In contrast, the other commands don’t perform per-item scripting: Sort-Object focuses on ordering items, Test-Connection checks reachability, and Out-Host simply writes output to the screen.

When you want to do something to every object that flows through a PowerShell pipeline, you need a command that runs a script block for each input item. This is exactly what the per-item processor does. ForEach-Object is designed for this role. It takes each object from the pipeline and executes the script block you provide, with the current object accessible inside the block as $_. This lets you transform, filter, or perform actions on every item as it passes through the pipeline. The shorthand alias for this is the percent sign, which is just a quicker way to write it.

For example, Get-Service | ForEach-Object { $_.Name } would print the name of each service. In contrast, the other commands don’t perform per-item scripting: Sort-Object focuses on ordering items, Test-Connection checks reachability, and Out-Host simply writes output to the screen.

Subscribe

Get the latest from Passetra

You can unsubscribe at any time. Read our privacy policy