PowerShell: Define Function
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
- Anything in function body that isn't captured is returned.
- Captured means assigned to a variable or redirected. 〔see PowerShell: Suppress Command Output〕
- When there are multiple outputs, they are collected in a array as return value.
- if no output, return value is
$null
.
# 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 can contain return statement with
return expression
or justreturn
. return
means the function exit at that point.return
does not suppress previous outputs.
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