To create a function, call the function keyword followed by a name for the function, then include your code inside a pair of curly braces.
function AddNumbers
{$args[0] + $args[1]}
AddNumbers 5 10
N.B you need to define the function before you call it.
Don't add brackets around the function parameters:
$result = AddNumbers (5, 10) --Wrong!
$result = AddNumbers 5 10 --right
To make the function available, either include it at the start of the script where it will be used or store it in your profile (the text file: "$Profile")
When you call the function name, the code within the function will run, A function can accept imported values either as arguments or through the pipeline. If the function returns any values, they can be assigned to variables or passed to other functions or cmdlets.
Function or Filter definition:
function [scope_type:]name
{
[ param(param_list) ]
script_block
}
filter [scope_type:]name
{
[ param(param_list) ]
script_block
}
The difference between a filter function and a regular function is the way they handle items passed through the pipeline:
With a regular function, pipeline objects are bound to the $input automatic variable, and execution is blocked until all input is received. The function then begins processing the data.
With a filter function, data is processes while it is being received, without waiting for all input. A filter receives each object from the pipeline through the $_ automatic variable, and the script block is processed for each object.
The param_list is an optional list of comma separated parameter names, these may also be preceded by their data types in brackets. This makes the function more readable than just using $args and also gives you the option to supply default values.
Examples
A function to find all files on the C: drive owned by a particular user:
function files_owned_by
{
Get-ChildItem -recurse C:\ | get-acl | where {$_.Owner -match $args[0]}
}
PS C:\> files_owned_by JDoe
A function to quickly list and set environment variables, like the old SET command (by Wes Haggard)
if (test-path alias:set) { remove-item alias:set > $null }
function set
{
[string]$var = $args
if ($var -eq "")
{get-childitem env: | sort-object name}
else
{
if ($var -match "^(\S*?)\s*=\s*(.*)$")
{set-item -force -path "env:$($matches[1])" -value $matches[2];}
else
{write-error "ERROR Usage: VAR=VALUE"}
}
}
PS C:\> Set testing=abc
A function with default values:
function sale_item
{
param([string]$description = "unknown",
[int]$price = 100)
Write-Output "$description ..... $price"
}
PS C:\> sale_item Hammer 250
A filter to find files owned by a specific user:
filter ownedbyme
{
if ($_.Owner -match "JDoe") {$_}
}
PS C:\>Get-ChildItem -recurse C:\ | Get-Acl | where {$_ | ownedbyme}
“The function of the imagination is not to make strange things settled, so much as to make settled things strange” - G. K. Chesterton
Related:
Ref vars - Passing a reference variable to a function.