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.

Don Jones

June 23, 2010

1 Min Read
ski tracks on a snowy landscape

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.

 

Sign up for the ITPro Today newsletter
Stay on top of the IT universe with commentary, news analysis, how-to's, and tips delivered to your inbox daily.

You May Also Like