PowerShell Parameters
A parameter is an input that a function accepts. Parameters let one function work with different values each time it runs.
Take one parameter by name
The param block declares the input. The call passes a value with the parameter name.
function Get-Greeting {
param([string]$Name)
"Hello, $Name"
}
Get-Greeting -Name "Ana"Take two parameters and use both
List each parameter in the param block, separated by a comma. The function body can use both values.
function Add-Numbers {
param([int]$First, [int]$Second)
$First + $Second
}
Add-Numbers -First 3 -Second 4Pass values in order without names
Positional values match parameters in their declared order. The first value goes to the first parameter.
function Add-Numbers {
param([int]$First, [int]$Second)
$First + $Second
}
Add-Numbers 5 6Example
function Get-FullName {
param([string]$First, [string]$Last)
"$First $Last"
}
Get-FullName -First "Ana" -Last "Silva"
Get-FullName "Sam" "Costa"Key points
- Parameter: an input that a function accepts.
- Declare parameters in a param block at the start of the function.
- Each parameter has a name that starts with a dollar sign.
- Call with named values by writing a dash, the parameter name, and the value.
- Call with positional values by writing the values in the declared order.
In this example, a function takes a first name and a last name and joins them with a space. The first call passes both values by name. The second call passes both values in order, without names.
Note
A parameter can carry a type, such as string or int, which shapes the value it accepts.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
Which call passes Ana to the Name parameter of Get-Greeting?