Parameters in PowerShell can be passed into a function or a script using the param() block.
The param() block and the $Mandatory argument
A parameter can be set as mandatory or optional by setting the Mandatory argument in the [Parameter()] attribute to $true (the default value is $false).
Here is an example of how to pass parameters as optional (the code is saved in a PowerShell script called script1.ps1).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# Define a function called CalculateMean which accepts # two parameters $Name(mandatory) and the other two are not. function CalculateMean{ # We did not explicitly mark $Math as Mandatory, # but PowerShell sets it optional by default. param( [Parameter(Mandatory=$true)][string]$Name, [Parameter(Mandatory=$false)]$Eng, $Math ) # Sum the values of $Eng and $Math $total = $Eng + $Math # Get the arithmetic of the two numbers $mean = $total/2 # return the total and the mean. return $total, $mean } # Call the CalculateMean function and pass $Name and $Eng $total, $mean = CalculateMean -Name "Allan" -Eng 67 Write-Host "Your total is $total and you mean mark is $mean" # Call the function and do not pass the Mandatory argument $Name $total, $mean = CalculateMean -Eng 67 -Math 89 Write-Host "Your total is $total and you mean mark is $mean" |
Passing optional parameters with a default value
As shown in the example below, you can pass a default value to an optional parameter.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
function CalculateMean{ # Passing a default value to $Math parameter. param( [Parameter(Mandatory=$true)][string]$Name, [Parameter(Mandatory=$false)]$Eng, $Math=50 ) # Sum the values of $Eng and $Math $total = $Eng + $Math # Get the arithmetic of the two numbers $mean = $total/2 # return the total and the mean. return $total, $mean } # Call the CalculateMean function and pass $Name and $Eng $total, $mean = CalculateMean -Name "Allan" -Eng 67 Write-Host "Your total is $total and you mean mark is $mean" |
Output:
Your total is 117 and your mean mark is 58.5
When the code above is executed without the value of $Math parameter, the default value of 50 is used, and therefore $total=67+50=117 and $mean=117/2 = 68.5.
Note 1: You can pass parameters into a script by adding the param() block and the parameters at the beginning of the script.
Note 2: A default value cannot be passed into a mandatory parameter. If you do so, the default value will be ignored.
Conclusion
You can pass the optional parameters to the PowerShell function or script using the param block and the Mandatory argument on the [Parameter()] variable, as shown in the examples discussed in this article. Additionally, we also learned how to pass default values for optional parameters.