PowerShell: Define Function

By Xah Lee. Date: . Last updated: .

Simple Example of Defining a Function

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

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.

Return value

# demo, of a function, anything not captured is returned, as array
function ff {
    "something";
    4;
}

# call
$x = ff

$x
# something
# 4

# return type is array
$x.gettype().name
# Object[]
function ff {
    "something";

    # suppress an output
    $null = 4;
}

# call
$x = ff

$x
# something

# return type is string
$x.gettype().name
# String

return statement

function ff {
    3;
    return 4;
    5;
}

# call
$x = ff

$x
# 3
# 4

# return type is array
$x.gettype().name
# Object[]

nested function

function can be nested.

function f ($x) {
    function g ($x) { $x + 1 }
    # g is local to f

    # call g
    g $x
}

f 3
# 4

PowerShell. Define Function