Functions and parameters

PowerShell · Practical · 12 min

Functions with proper parameters behave like real cmdlets: tab completion, validation and help for free.

Define a function with function Verb-Noun { param(...) ... }. Use an approved verb so it fits in with the built-in commands. The param() block declares parameters:

  • a type like [string] or [int] converts and validates the input,
  • a default value: [string]$Word = 'Hello',
  • [Parameter(Mandatory)] prompts if the value is missing (or fails in non-interactive runs),
  • validation attributes: [ValidateSet('a','b')], [ValidateRange(1,10)], [ValidateNotNullOrEmpty()], [ValidatePattern('^\d+$')],
  • [switch]$Force is an on/off flag that is $true when present.

Calling works like any cmdlet: Get-Greeting -Name Ada -Shout, or positionally Get-Greeting Ada. Never call with parentheses and commas: Add(2, 3) passes a single array to the first parameter. Parentheses and commas are only for .NET methods.

What a function returns is everything it outputs: any value not assigned or discarded goes to the pipeline. return $x just outputs $x and exits. Discard unwanted output with $null = ... or | Out-Null.

Tab completion works for your parameters, and a comment-based help block (<# .SYNOPSIS ... #>) makes Get-Help work for your function.

Example

function Get-Greeting {
  param(
    [Parameter(Mandatory)]
    [string]$Name,
    [ValidateSet('Hello', 'Hi', 'Welcome')]
    [string]$Word = 'Hello',
    [switch]$Shout
  )
  $text = "$Word, $Name!"
  if ($Shout) { $text = $text.ToUpper() }
  $text                              # output = return value
}
Get-Greeting -Name Ada               # Hello, Ada!
Get-Greeting Bob -Word Hi -Shout     # HI, BOB!
# Get-Greeting -Name Cy -Word Yo     # error: "Yo" does not belong to the set
function Add-Numbers($a, $b) { $a + $b }
Add-Numbers 2 3                      # 5      (spaces, no commas)
Add-Numbers(2, 3)                    # 2 / 3  ($a got the array 2,3; $b is empty)

Remember

  • param() with types, defaults, Mandatory, Validate* and [switch]
  • Call functions like cmdlets: Name -Param value, no parentheses or commas
  • Every uncaptured value is output; return just exits

Watch out for

  • Calling MyFunc($a, $b) like a method, which passes one array argument.

Check yourself

  1. How do you call a function `Add-Numbers($a, $b)` with 2 and 3?
  2. What is the value of a [switch]$Force parameter when the caller omits -Force?

Sign in to answer, see the explanations, and get this lesson back as a quick review later.

Official docs: learn.microsoft.com/en-us/powershell/module/microsoft.powershell.core/about/about_functions_advanced_parameters

Functions and parameters · PowerShell · Topolearn