🎓 A1Learner
🔍
0 of 46 lessons completed

PowerShell Tool Functions

A tool function is a function written for other people to reuse. It takes pipeline input, gives predictable output, and keeps the same shape every time.

A process block handles each pipeline item

The process block runs once per item from the pipeline. Each word comes out shouted on its own line.

function Get-Shout {
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline)][string]$Text)
    process { $Text.ToUpper() }
}
"hello", "world" | Get-Shout

A typed parameter keeps input predictable

The Name parameter only accepts text. Each piped name comes back with its length.

function Get-NameLength {
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline)][string]$Name)
    process { $Name.Length }
}
"Ana", "Samuel" | Get-NameLength

A tool works from the pipeline and by name

The same tool accepts piped input and a named argument. Both calls print the same shape of output.

function Get-Shout {
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline)][string]$Text)
    process { $Text.ToUpper() }
}
"hello" | Get-Shout
Get-Shout -Text "bye"

Example

function Get-Greeting {
    [CmdletBinding()]
    param([Parameter(ValueFromPipeline)][string]$Name, [string]$Word = "Hello")
    process { "$Word, $Name" }
}
"Ana", "Ben" | Get-Greeting -Word "Hi"

Key points

  • Advanced function: a function with the CmdletBinding attribute, which gives it standard behaviour.
  • Process block: the part of a function that runs once for each pipeline item.
  • ValueFromPipeline: a parameter setting that lets the pipeline fill that parameter.
  • Use a typed parameter to accept only the right kind of input.
  • Predictable output: the function prints only its result, one value per item, in the same shape every time.

In this example, Get-Greeting is an advanced function with a pipeline parameter and a word parameter with a default. Two names flow through the pipeline, and each one prints a greeting in the same shape.

Note

A tool function never prints extra chat. Extra lines break the pipeline for the next command.

Try it Yourself

Edit the code, then press Run.

Running is simulated

Exercise

What does a process block do?