PowerShell Default Values
A default value is the value a parameter uses when the caller gives none. Defaults make a parameter optional, so a call can leave it out.
Give a text parameter a default
The default sits in the param block after the equals sign. A call with no value uses it.
function Get-Greeting {
param([string]$Name = "friend")
"Hello, $Name"
}
Get-Greeting
Get-Greeting -Name "Ana"Give a number parameter a default
Defaults work for numbers just as they work for text. The call without a value gets the default number.
function Get-Count {
param([int]$Count = 5)
$Count
}
Get-Count
Get-Count -Count 9Mix a default with a value you give
A call can give one parameter and leave another out. The given parameter uses its own value, and the other uses its default.
function Get-Message {
param([string]$Name = "friend", [string]$Greeting = "Hello")
"$Greeting, $Name"
}
Get-Message
Get-Message -Name "Ana"Example
function Get-Profile {
param([string]$Name = "Guest", [int]$Age = 18)
"$Name is $Age years old"
}
Get-Profile
Get-Profile -Name "Ana"
Get-Profile -Name "Sam" -Age 31Key points
- Default value: the value a parameter uses when the caller gives none.
- Write a default after the parameter name with an equals sign and the value.
- A call that leaves the parameter out uses the default.
- A call that gives the parameter uses its own value instead.
- A function can mix parameters with defaults and parameters without them.
In this example, a function builds a profile line from a name and an age, both with defaults. The first call uses both defaults. The second call gives only the name. The third call gives both values.
Note
Put a parameter with a default after any parameter that has no default, so positional calls still line up.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
For param([string]$Name = "friend"), what value does $Name hold in a call that passes nothing?