Optional Parameters in Powershell

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).

Passing optional parameters with a default value

As shown in the example below, you can pass a default value to an optional parameter.


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.


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.