PowerShell: Function Parameters
Named Parameters
Two syntax for named parameters.
simple, traditional:
function fname (param1, param2) {
statements
}
use the keyword param
in function body:
function fname {
param (param1, param2);
statements
}
💡 TIP: using param in body is recommended, because when param gets complex, it is less clutter.
function f ($x , $y) { $x + $y } # call f 3 4 # 7 # call with param name f -x 3 -y 4 # 7
# example of defining function parameter using param 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 Parameter (for On or Off)
Add [switch]
in front of the parameter name.
function f { param ([switch] $x) if ($x) { Write-Host "yes" } else { Write-Host "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
parameter type declaration
You can declare type for parameter.
For example
[int] $x
.
〔see Value Types〕
# declare param type function f ([int]$x) {$x+1} f 3 # 4