PowerShell: 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
Allowed characters in function name
Function name can contain: dash -, lowline _, question mark ?, exclamation !. Case does not matter.
By PowerShell convension, you should just use letters and HYPHEN-MINUS -.
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
}
or
function name {
param (param1, param2);
statements
}
function f ($x , $y) { $x + $y } # call f 3 4 # 7 # call with param name f -x 3 -y 4 # 7
function f { param ($x , $y) $x + $y } # call f 3 4 # 7 # call with param name f -x 3 -y 4 # 7
Default Value for Named Parameter
Example of adding default value:
param ($x = 3 , $y = 4)
function f { param ($x = 3 , $y = 4) $x + $y } # call f # 7
Switch Parameters
Add [switch]
in front of the parameter name.
function f { param ([switch] $x) if ($x) { echo "yes" } else { echo "no" } } f -x # yes f # no
Positional Parameters
$args[0]
$args[0]
, $args[1]
are the parameter values.
function f { $args[0] + $args[1] } f 3 4 # 7
param type declaration optional
You can declare type for parameter.
For example
[int] $x
.
[see PowerShell: Value Types]
# declare param type function f ([int]$x) {$x+1} f 3 # 4
return statement optional
PowerShell functions are best thought of as a collection of statements, not a functional programing function that returns a value.
PowerShell function can contain return statement with return expression
or just return
. The function will exit at that point.
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