This page tries to demonstrate some usages of $args and the param statement.
Not explicitly named parameters
It's possible to define a function that does not explicitly name its parameters. The values of the parameters can then be accessed within the function using the $args array.
This is similar to the @_ variable that stores the values that are passed to a Perlsub.
function add {
$args[0] + $args[1]
}
$sum = add 19 23
write-output "sum is $sum"
#
# sum is 42
$sum = add "foo" "bar"
write-output "sum is $sum"
#
# sum is foobar
The types of the parameters can be constrained to make sure that the function gets what it expects.
function add ([int]$param_1, [int]$param_2) {
$param_1 + $param_2
}
$sum = add 19 23
write-output "sum is $sum"
#
# sum is 42
# $sum = add "foo" "bar"
#
# Because add takes typed parameter, trying to
# invoke add with strings resultes in the following
# error:
# Cannot process argument transformation on parameter 'param_1'.
# Cannot convert value "foo" to type "System.Int32".
# Error: "Input string was not in a correct format.
#
The parameters can be listed more explicitly within a param block:
function add {
#
# Parameters can also be specified more explicitely
# within the param() statement:
#
param (
[int] $param_1,
[int] $param_2
)
$param_1 + $param_2
}
$sum = add 19 23
write-output "sum is $sum"
An interesting benefit of annotating a parameter with validateSet is that it allows to «cycle through» the listed values with the tabulator (tab-completion) when entering the respective parameter.
Default values
A parameter can be declared with a default value which is used if the parameter is not explicitly given a value when the function is invoked:
param() can be prefixed with [cmdletBinding()] which causes the corresponding function to turn into a cmdLet, thus adding common parameters (such as -verbose or -errorAction]) automatically to the function/cmdlet:
function i-am-a-cmdlet {
[cmdletBinding()]
param (
[string] $text
)
write-host $text
write-verbose "hello, I am a cmdlet"
}
This function/cmdlet can now be invoked with common parameters, for example like so: