Q. How can I make a PowerShell script or function have mandatory parameters?
There are a couple of ways to have mandatory parameters. The best way is to use the [CmdletBinding()] parameter syntax, as described in PowerShell's about_functions_advanced_parameters Help topic.
June 23, 2010
Q. How can I make a PowerShell script or function have mandatory parameters?
A. There are a couple of ways to have mandatory parameters. The best way is to use the \[CmdletBinding()\] parameter syntax, as described in PowerShell's about_functions_advanced_parameters Help topic. This attribute allows you to add a Mandatory=$true attribute to the parameters that you want to make mandatory.
Another approach is to assign a "default" value that throws an error:
Param($myparam=$(throw ‘This is required.'))
If the parameter isn't provided, an error would be thrown. I think that syntax is a bit harder to read than the [CmdletBinding()] technique, though.
Do you have a Windows PowerShell question? Find more PowerShell FAQs, articles, and other resources at windowsitpro.com/go/DonJonesPowerShell.
About the Author
You May Also Like