PowerShell: Define Function

By Xah Lee. Date: . Last updated: .

Simple Example of Defining a Function

Simple example of defining a function.

# simple function definition. No parameters
function f () {dir}

# call a function
f
# return dir list
# 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

Return value

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