This write-up will cover the aspects to make the parameters mandatory.
How to Make Parameters Mandatory in PowerShell?
The PowerShell attribute “[Parameter()]” is utilized to add special behaviors such as Position, Help Message, or Mandatory. More specifically, a mandatory parameter is used to make the parameters mandatory.
The parameter in PowerShell can be made mandatory by adding the “Mandatory=$true” attribute to the parameter description. If you want to make the parameter optional, leave the “Mandatory” statement empty.
Example 1: Passing Mandatory Parameters in PowerShell
In this example, we will make parameters mandatory in PowerShell:
param(
[Parameter(Mandatory=$true)]
[string]$Name,
[Parameter(Mandatory=$true)]
[string]$Profession)
"$Name and $Profession"
}
test John Doctor
According to the above code:
- First, create a function and add the “param()” block inside it.
- Each parameter inside the “param()” block is associated with the “[Parameter()]” method.
- Inside the “[Parameter()]” method, the “Mandatory” attribute value is assigned, and it is set to “$True”, which means it is enabled to take the value from the user.
- Outside the function, the function name is written, which is “test”. The two arguments to be passed inside the parameter are “John” and “Doctor”:
It can be observed from the output that the values have been successfully passed to the mandatory parameter.
Example 2: Not Passing Any Mandatory Parameters in PowerShell
Let’s test the function by not passing the mandatory parameter’s value to it when it is enabled:
As you can see, the script returned an error because the value was not passed to the mandatory parameter.
Example 3: Leaving Mandatory Parameter Optional in PowerShell
In this example, let’s leave the mandatory parameter optional. To do so, leave the “[Parameter()]” attribute out, as it is demonstrated below:
That was all about making parameters mandatory in PowerShell.
Conclusion
The parameters can be made mandatory by adding the “[Parameter()]” method inside the “param()” method. Within this method, add the “Mandatory” attribute value and assign the “$True” value to it in order to enable it. This write-up guided about making the parameters mandatory in PowerShell.