PowerShell Functions
A function is a named block of code you can call again and again. Functions keep scripts short, readable and testable. In PowerShell they behave just like cmdlets: they take named parameters, accept pipeline input and output objects.
Defining and calling
function Get-Greeting {
'Hello from a function!'
}
Get-Greeting
Get-GreetingHello from a function!
Hello from a function!
Name functions with the Verb-Noun convention and an approved verb (Get-Verb), just like cmdlets. Call them without parentheses or commas, the way you call any command.
Parameters
Declare parameters in a param() block. Give them types and default values where it makes sense:
function Get-Discount {
param(
[double]$Price,
[int]$Percent = 10
)
$Price * (100 - $Percent) / 100
}
Get-Discount -Price 80
Get-Discount -Price 80 -Percent 25
Get-Discount 80 50 # positional, in declaration order72
60
40
The type converts the arguments ('80' would become 80.0) and rejects values that can't be converted.
Warning: Never call a PowerShell function like a C# method.
Get-Discount(80, 25)passes one argument, the array80, 25, to-Price. Use spaces:Get-Discount 80 25.
Switch parameters
A [switch] parameter is an on/off flag, like -Recurse on cmdlets:
function Format-Name {
param(
[string]$Name,
[switch]$Shout
)
if ($Shout) { $Name.ToUpper() + '!' } else { $Name }
}
Format-Name -Name 'ada'
Format-Name -Name 'ada' -Shoutada
ADA!
Return values: everything is output
A function returns every value it outputs, not just the one after return. return simply outputs its value and leaves the function:
function Test-Output {
'first'
$list = [System.Collections.ArrayList]::new()
$list.Add('x') # .Add() returns the index -> leaks into the output!
return 'last'
'never reached'
}
$result = Test-Output
$result.Count
$result -join ' | '3
first | 0 | last
The 0 came from ArrayList.Add(), which returns the index of the new item. This "leaking" output is the most common function bug. Silence such calls with $null = …, [void](…) or | Out-Null.
Returning objects
Return structured data, not formatted text, so callers can work with it:
function Measure-Text {
param([string]$Text)
$words = @($Text -split '\s+' | Where-Object { $_ })
[pscustomobject]@{
Characters = $Text.Length
Words = $words.Count
Longest = ($words | Sort-Object Length -Descending | Select-Object -First 1)
}
}
$stats = Measure-Text 'PowerShell functions return rich objects'
$stats.Words
$stats.Longest
$stats5
PowerShell
Characters Words Longest
---------- ----- -------
40 5 PowerShell
$args and simple functions
Without a param() block, the arguments land in the automatic array $args. You can also write a quick parameter list in parentheses after the name:
function Add-All { ($args | Measure-Object -Sum).Sum }
Add-All 1 2 3 4
function Join-Path2($Parent, $Child) { "$Parent/$Child" }
Join-Path2 'logs' 'today.txt'10
logs/today.txt
Both are fine for tiny helpers. For anything you'll reuse, use a typed param() block, which also enables help, validation and tab completion.
Tip: Functions must be defined before the line that calls them, because a script runs from top to bottom.
Test yourself
How do you call function Add-Numbers { param($A, $B) $A + $B } correctly?
- Add-Numbers(2, 3)
- Add-Numbers 2 3
- Add-Numbers(2; 3)
- Add-Numbers[2, 3]
A function outputs 'a', then runs return 'b'. What does the caller receive?
- 'b'
- 'a'
- 'a' and 'b'
- Nothing
Which parameter type creates an on/off flag such as -Force?
- [bool]
- [switch]
- [flag]
- [int]