PowerShell Script Parameters
A script parameter is a value passed to a script when it runs. It lets one script behave differently without editing its code.
A parameter with a default value
The param block sits at the top of the script. With no arguments given, Name uses its default.
param([string]$Name = "friend")
"Hello, $Name"Two parameters with defaults
A param block can list more than one parameter. Each one keeps its own default value.
param([string]$Name = "Ana", [int]$Age = 30)
"$Name is $Age years old"A number parameter in a calculation
A typed parameter can be used like any variable. Count doubles to 6 below.
param([int]$Count = 3)
$Count * 2Example
param([string]$Name = "Ana", [string]$Topic = "PowerShell", [int]$Minutes = 5)
"$Name is learning $Topic for $Minutes minutes"Key points
- Parameter: a named value a script accepts at its start.
- Param block: the param block sits at the top of a script and lists its parameters.
- Default: a default value is used when the caller gives no value.
- Named value: you pass a value by its parameter name, such as -Name "Ana".
- Type: a type such as [string] or [int] controls what kind of value is accepted.
In this example, the param block lists three parameters with defaults. The script runs with no arguments, so every default is used. The last line prints one sentence built from the three values.
Note
a script run with no arguments uses every default value.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What value does a script parameter use when the script runs with no arguments?