Skip navigation
ski tracks on a snowy landscape

Q. How can I make a PowerShell script or function have mandatory parameters?

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.

 

Hide comments

Comments

  • Allowed HTML tags: <em> <strong> <blockquote> <br> <p>

Plain text

  • No HTML tags allowed.
  • Web page addresses and e-mail addresses turn into links automatically.
  • Lines and paragraphs break automatically.
Publish