This article discusses how to pass parameters into a PowerShell script from the command line. We will start by discussing the syntax of the needed commands and then work through some examples to apply the knowledge.
The “param” Block
To run a PowerShell script with parameters, we need to define a “param” block containing all parameters we need at the beginning of the script.
The general syntax for the “param” block is as follows:
1 2 3 4 5 6 7 8 9 10 11 12 13 |
param( [Attribute_1] [Attribute_2] … [Attribute_n] [Data-Type][Parameter1_Name][=Default_Value], [Attribute_1] [Attribute_2] … [Attribute_n] [Data-Type][Parameter2_Name][=Default_Value], … ) |
Where:
- Attribute – specifies the conditions for valid value(s). In most cases, it is used to validate the input parameters (Don’t worry if that is not clear, we will work on examples),
- Data-Type is the parameter’s data type, e.g., string, bool, or int. If you pass a different type parameter, PowerShell will attempt to convert it into the specified type.
- Default_Value is a fallback value if a mandatory parameter is not supplied,
- Parameter_Name is the name of the first parameter.
Let’s discuss two of the attributes that are commonly used.
The Parameter Attribute
The [Parameter()] attribute is an essential attribute when checking the parameters that have been passed. It accepts several arguments, including
- Mandatory – this argument indicates if a parameter is required or optional. It accepts the values $true or $false (default).
- Position – specifies the position of the parameter during script execution. If the user passes parameter values without the name, they can assign the position using this argument. By default, PowerShell assigns Position=0 to the first parameter issued, Position=1 for the second parameter value, etc.
- HelpMessage – specifies the help message a user should be greeted with if they do not pass a mandatory parameter or the validation fails.
Validation Attributes
These attributes are used to specify the valid parameter values. Some attributes in this category include ValidateSet, ValidatePattern, and ValidateScript (we will learn more about this in the examples).
Next, let’s go through examples. However, before we do that, please note the following:
- All commands in this article were executed on PowerShell 7.3.2. You can check the PowerShell version by running the command “Get-Host” from PowerShell itself.
- All lines starting with the “#” symbol are comments.
Examples
The following examples will build on the concepts we have discussed above. Each example will explain a specific and unique concept.
Example 1: A script with no attributes – a basic example
The following script is saved as “01general.ps1”. The param block defines three parameters with no supporting attributes.
File: 01general.ps1
1 2 3 4 5 6 7 8 9 10 11 |
# The script accepts three parameters param( $Name, $Eng, $Math ) # Print the following message into the console Write-Host "Hello, $Name, you scored $Eng`% in English and $Math`% in Mathematics" # Compute the mean of Eng and Math and print the result to the console. $mean = ($Eng + $Math)/2 Write-Host "Your mean is $mean`%" |
Then you can run the script using the following commands
1 2 |
cd <path_to_the_folder_containing_the_script> .\script_name.ps1 -Param1 <value> -Param2 <value> … |
In our case, we will navigate into the folder with the script using the cd command and execute the following commands.
1 2 3 4 5 6 |
# Passing all three parameters .\01general.ps1 -Name Tomasz -Eng 56 -Math 67 # None of the Parameters are mandatory. This -Eng parameter is not passed in this case. .\01general.ps1 -Name Tomasz -Math 56 # You don't have to pass the parameter names when calling .\01general.ps1 Tomasz 56 |
In the last example, parameter names are not provided. By default, parameters are positional. That is, PowerShell can infer the parameter being passed based on position. That means “Tomasz” is assigned to the first parameter (-Name), 56 is assigned to the second parameter (-Eng), and PowerShell assumes that -Math was not passed.
Example 2: Mandatory and optional parameters
As explained, a parameter is set as optional or mandatory using the Mandatory argument on the [Parameter()] attribute. Here is an example with $Name and $Math as required parameters and $Eng as optional.
File: make_variables_mandatory.ps1
1 2 3 4 5 6 7 8 |
param( [Parameter(Mandatory=$true)] $Name, [Parameter(Mandatory=$false)] $Eng, [Parameter(Mandatory=$true)] $Math ) Write-Host "Hello, $Name, you scored $Eng`% in English and $Math`% in Mathematics." $mean = ($Eng + $Math)/2 Write-Host "Your mean is $mean`%." |
Note from the code examples below that PowerShell will prompt you to provide mandatory parameters if you do not supply them.
1 2 3 4 5 6 |
# Strings with spaces should be in quotes .\make_variables_mandatory.ps1 -Name "Kiprono Elijah" -Math 56 # Mandatory value not passed -PowerShell will prompt you to provide the mandatory parameter. .\make_variables_mandatory.ps1 -Name "Kiprono Elijah" -Eng 54 # Positional parameters "Kiprono Elijah" is assigned to name and -Eng 56. -Math not given # .\make_variables_mandatory.ps1 "Kiprono Elijah" 56 |
Example 3: Specifying the position of positional parameters
When you issue parameters without names on the command line, PowerShell assumes that the first value belongs to the first parameter, the second value belongs to the second parameter, etc.
You can change that using the Position argument of the [Parameter()] attributes, as shown below.
File: specify_position.ps1
1 2 3 4 5 6 7 8 |
param( [Parameter(Mandatory=$true, Position=0)] $Name, [Parameter(Mandatory=$true, Position=2)] $Eng, [Parameter(Mandatory=$true, Position=1)] $Math ) Write-Host "Hello, $Name, you scored $Eng`% in English and $Math`% in Mathematics." $mean = ($Eng + $Math)/2 Write-Host "Your mean is $mean`%." |
In the execution shown in the Figure below, the first value is assigned to the $Name parameter, the second to $Math, and the last to $Eng.
Example 4: Using default values, supplying help message, and validating parameter values
This example shows how to use default values and validate input parameter values using ValidateSet, ValidateRange, and, ValidateScript.
The following line shows a mandatory parameter with a HelpMessage. PowerShell will prompt the user to input the value alongside the help message if the parameter is not supplied in the command line.
1 2 3 4 |
param( [Parameter(Mandatory=$true, HelpMessage="Enter the name of the candidate. ")] $Name ) |
The ValidateSet attribute specifies a set of valid values for the parameter. The following snippet shows a $ExamType parameter that accepts two values only – “cat1” or “cat2”.
1 2 3 4 5 |
param( [Parameter(Mandatory=$true, HelpMessage="Enter the Exam Type. You can only use cat1 or cat2 ")] [ValidateSet(“cat1", “cat2”)] $ExamType ) |
ValidateRange specifies a numeric range for a given parameter. For example, ValidateRange(0,100) means the parameter in question must be between 0 and 100.
The ValidateScript attribute specifies a script that is used to validate a parameter. It allows the user to create a custom validation scheme for a specific purpose. For example, [ValidateScript({($_ -is [string]) -and ($_.Length -le 10)})] means that a given parameter must be a string of fewer than ten characters.
Let’s put all that together in a PowerShell script.
File: validate_parameter_values.ps1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
param( [Parameter(Mandatory=$true, Position=0)] [ValidateScript({($_ -is [string]) -and ($_.Length -le 10)})] [ValidatePattern("^[a-z A-Z]+$")] # a regex. $Name must be made of alphabetical letters or space $Name, [Parameter(Mandatory=$true, Position=2)] [ValidateRange(0,100)] $Eng, [Parameter(Mandatory=$true, Position=1)] [ValidateRange(0,100)] $Math, [Parameter(Mandatory=$true, Position=3)] [ValidateSet("Cat1", "Cat2")] $ExamType ) Write-Host "Hello, $Name, you scored $Eng`% in English and $Math`% in Mathematics." $mean = ($Eng + $Math)/2 Write-Host "Your mean is $mean`%." |
Then we can call the script with these commands.
1 2 3 4 5 6 7 8 |
# -Math must be between 0 and 100. This will fail .\validate_parameter_values.ps1 -Name "Ammon" -Eng 5 -Math 105 -ExamType Cat1 # The -Name is too long. This will fail as well .\validate_parameter_values.ps1 -Name "Ammon Kipkirui" -Eng 5 -Math 11 -ExamType Cat1 # -ExamType can only be “Cat1" or “Cat2" and not “Cat3". This will fail also. .\validate_parameter_values.ps1 -Name "Ammon" -Eng 5 -Math 11 -ExamType Cat3 # All validation tests will be passed .\validate_parameter_values.ps1 -Name "Ammon" -Eng 5 -Math 11 -ExamType Cat1 |
Conclusion
This article discussed how to pass parameters to a PowerShell script. The first section discussed the syntax of the “param” block – the key command to pass the parameters to a script.
The second section covered four examples of how to use param. We discussed how to pass mandatory and optional parameters and validate the parameter values passed by the user.