POWERSHELL / CHAPTER 12

Build reusable pipeline commands

Advanced

Process one input object at a time with validated parameters.

By the end of this chapter

  • Use begin, process, and end for distinct phases
  • Bind pipeline input to a declared parameter
  • Support preview correctly when implementing changes

The idea

An advanced function can participate in the pipeline through a parameter marked ValueFromPipeline. Begin initializes state once, process handles each input object, and end emits a final summary or completes aggregation. Keep per-record work in process; placing it only in end does not provide the intended record-by-record behavior. Parameter validation states input constraints before the main calculation proceeds.

For functions that change external state, SupportsShouldProcess exposes preview and confirmation behavior, but the function must actually call $PSCmdlet.ShouldProcess and honor its result before making the change. The attribute alone is not protection. Return structured results with enough information for callers to inspect the outcome, and keep diagnostics separate. Test empty input, multiple records, invalid arguments, and the preview path as distinct contracts.

PowerShell example
function Measure-Positive {
  [CmdletBinding()]
  param([Parameter(ValueFromPipeline)][int]$Value)
  begin { $count = 0 }
  process { if ($Value -gt 0) { $count++ } }
  end { [pscustomobject]@{ PositiveCount = $count } }
}
(@(-1, 2, 0, 3) | Measure-Positive).PositiveCount
Result
2

Begin initializes one counter, process sees all four input objects, and end emits one structured summary. Only the two positive values contribute.

Try it yourself

Create an advanced function that accepts pipeline records and emits one validated aggregate summary.

Use your own editor for this exercise. Runnable challenges on CodeQuest are available for JavaScript, Python, and SQL.

CHECK YOUR UNDERSTANDING

Chapter checkpoint

Which named block performs one-time initialization for a function’s pipeline invocation?