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


function name {statements}

param type declaration optional

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

f 3
# returns 4

return statement optional

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

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 name (param1, param2) { statements }


function name { param (param1, param2); statements }

function f {
param ($x , $y);
$x + $y

# call
f 2 3
# return 5

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

Positional Parameters


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

function ff {
$args[0] + $args[1]

f 3 4
# returns 7

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 $_
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 Begin/Process/End blocks, the function behaves the same as if all statements are in End block.

function f { process { "yay " + $_ } }

dir | f
# prints yay full path




Script Examples