Functions
A function is a named, reusable block of code. In PowerShell, a function behaves just like a cmdlet: you call it by name, pass parameters, and pipe its output.
function Get-Greeting {
param([string]$Name = 'world')
"Hello, $Name!"
}
Get-Greeting
Get-Greeting -Name Ada
Get-Greeting Linus
Hello, world!
Hello, Ada!
Hello, Linus!
- Name functions
Verb-Nounwith an approved verb, like cmdlets. - Parameters go in a
param()block, exactly like script parameters. - Call a function with spaces between arguments — never with parentheses and commas.
Everything uncaptured is output
A function's output is every value it doesn't capture or discard —
not just what follows return:
function Get-Numbers {
'starting'
$list = [System.Collections.Generic.List[int]]::new()
$list.Add(1)
$list.Add(2)
return $list
}
$result = Get-Numbers
$result.Count
$result[0]
3
starting
The function returned three values: the string 'starting' and the
two numbers in the list (PowerShell unrolls collections as they're
output). Stray output is the most common function bug — silence
unwanted values with $null = ... or | Out-Null, and use
Write-Verbose for progress messages.
return exits the function; return $x outputs $x and then exits.
Common mistakes
function Add-Numbers {
param([int]$A, [int]$B)
$A + $B
}
Add-Numbers 2 3
Add-Numbers(2, 3)
5
Add-Numbers: C:\demo\script.ps1:7
Line |
7 | Add-Numbers(2, 3)
| ~~~~~~
| Cannot process argument transformation on parameter 'A'. Cannot convert the "System.Object[]" value of type
| "System.Object[]" to type "System.Int32".
Add-Numbers(2, 3) passes one argument — the array 2, 3 — to $A.
It can't convert an array to [int], so it fails. Use
Add-Numbers 2 3 or, better, Add-Numbers -A 2 -B 3.
Practice
Write Get-Area that takes -Width and -Height and returns their
product.
Show solution
function Get-Area {
param([double]$Width, [double]$Height)
$Width * $Height
}
Get-Area -Width 4 -Height 2.5
10