PowerShell: Function Body (begin process end)

By Xah Lee. Date: . Last updated: .

begin end process blocks

A function body usually contain the following blocks

Begin {statements}

Runs once when the function begins to run.

Process {statements}
  • If the function is invoked without pipeline input, the process block is run only once.
  • If the function is invoked with pipeline input, the process block is runs once for each piped object. If the pipeline input is empty, the process block does not run.

The current piped object is represented by $_

function f { process { "yay " + $_ } }

dir | f
# prints yay full path
End {statements}

Use this block to provide optional one-time post-processing for the function.

Runs once when all piped object are received.

Clean {statements}

The clean block was added in PowerShell 7.3.

The clean block is a convenient way for users to clean up resources that span across the begin, process, and end blocks. It's semantically similar to a finally block that covers all other named blocks of a script function or a script cmdlet. Resource cleanup is enforced for the following scenarios:

  • when the pipeline execution finishes without terminating error
  • when the pipeline execution is interrupted due to terminating error
  • when the pipeline is truncated, for example: Select-Object -First
  • when the pipeline is stopped by Ctrl+c or StopProcessing()

The clean block discards any output written to the Success stream.

PowerShell. Define Function