PowerShell: Function

By Xah Lee. Date: . Last updated: .

Simple example of defining a function.

# simple function definition
function f ($x, $y) {$x+$y}

# call a function
f 3 4
# returns 7

# or
f -x 3 -y 4
# returns 7

Allowed characters in function name

Function name can contain: hyphen -, lowline _, question mark ?, exclamation !. Case does not matter.

By PowerShell convension, you should just use letters and hyphen -.

Semicolon Optional If Newline

If each statement is on a line by itself, you do not need semicolon ; at the end of the statement. Otherwise, statements should be separated by semicolon.

Named Parameters

There are two syntax for named parameters.

function fname (param1, param2) { statements }
If you are writing a simple function, use this.
function f ($x , $y) {
 $x + $y
}

# call
f 3 4
# 7

# call with param name
f -x 3 -y 4
# 7
function fname { param (param1, param2); statements }
This param form allows you to declare advanced param validation.
function f {
 param ($x , $y)
 $x + $y
}

# call
f 3 4
# 7

# call with param name
f -x 3 -y 4
# 7

Default Value for Named Parameter

Example of adding default value: param ($x = 3 , $y = 4)

function f {
param ($x = 3 , $y = 4)
$x + $y
}

# call
f
# 7

Switch Parameters

Add [switch] in front of the parameter name.

function f {
param ([switch] $x)
if ($x) { echo "yes" } else { echo "no" }
}

f -x
# yes

f
# no

Positional Parameters

$args[0]

$args[0], $args[1] are the parameter values.

function f {
$args[0] + $args[1]
}

f 3 4
# 7

parameter type declaration

You can declare type for parameter. For example [int] $x. [see Value Types]

# declare param type
function f ([int]$x) {$x+1}

f 3
# 4

return statement optional

PowerShell function can contain return statement with return expression or just return. The function will exit at that point.

Accept Pipeline

to write a function that takes piped input, use one of the following in function body:

Begin {statements}
Runs once when the function begins to run.
Process {statements}
Runs once for each piped object. The current piped object is represented by $_
function f { process { "yay " + $_ } }

dir | f
# prints yay full path
End {statements}
Runs once when all piped object are received.

If the function contains any of these block, any code outside are ignored.

If a function does not contain any of these blocks, the function behaves the same as if all statements are in End block.

nested function

function can be nested.

function f ($x) {
 function g ($x) { $x +1 }
 g $x
}

f 3
# 4