05 / REUSABLE AUTOMATION · LESSON 18

Build a small reusable function

Write and call a function with a typed parameter.

14 min · learn at your pace

Put a name around useful work

A function groups statements under a name. Use the familiar Verb-Noun style for your own tools:

function Get-Greeting {
    param([string]$Name)
    "Hello, $Name"
}
Get-Greeting -Name 'Ada'

A function can use the same comparisons, loops, and pipelines as a script. Give it parameters instead of making it depend on variables from another part of your session.

Understand output

PowerShell sends uncaptured expressions to the output stream. A function does not need return to produce a result. return can end the function early, but earlier output still counts.

For example, an extra diagnostic string inside a function can accidentally become part of its returned data. Use Write-Verbose for optional diagnostics in an advanced function, or keep your function's output deliberately focused.

Type annotations such as [int] help define your interface. Validation attributes can enforce stronger rules when you need them. Start with one responsibility and test its boundary values.

Try an example.ps1
function Get-Greeting {
    param([string]$Name)
    "Hello, $Name"
}
Get-Greeting -Name 'Ada'
YOUR TURN

Put it into practice.

Define Get-DiskState with an integer parameter UsedPercent. Return Watch when UsedPercent is 80 or more, and Healthy otherwise. Call it once with 85 to try it.

See an explained solution
One way to solve it.ps1
function Get-DiskState {
    param([int]$UsedPercent)
    if ($UsedPercent -ge 80) { 'Watch' } else { 'Healthy' }
}
Get-DiskState -UsedPercent 85

The function depends only on its parameter, so callers can reuse it for any device. The checks exercise both sides of the boundary.