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 statement optional

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

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