Create a mandatory parameter if another parameter is chosen

Welcome Forums General PowerShell Q&A Create a mandatory parameter if another parameter is chosen

This topic contains 3 replies, has 3 voices, and was last updated by

 
Keymaster
2 years, 8 months ago.

  • Author
    Posts
  • #34868

    Participant
    Points: 0
    Rank: Member

    Is it possible to define a parameter that is only mandatory if another parameter is set?

    fast example:

    param (
      [parameter(mandatory=$true)][string][ValidateSet("Option1","Option2")]$Mode,
      [parameter][string]$Option
      )
    

    Basically let's say I'd like to set $Option to mandatory but _only_ if $mode="Option2". Obviously I can do this easily enough in the script outside of the param block, but I figured I'd ask if there was a more elegant way?

  • #34869

    Member
    Points: 0
    Rank: Member

    Nope. You'll have to add that validation logic inside the function somewhere. (Usually in the Begin block, but might need to be in Process if either of those parameters can accept pipeline input.)

  • #34870

    Member
    Points: 0
    Rank: Member

    Well, technically you can use dynamic parameters, but that's even less friendly. 🙂

  • #34871

    Keymaster
    Points: 1
    Rank: Member

    You can do what you're asking – that's what parameter sets are for – if you approach the logic slightly differently. Instead of an "Option" switch...

    Set A:
    -Option1

    Set B:
    -Option2 -Mode

    Where -Mode is always mandatory, but only gets engaged if run with -Option2. This is more the pattern you see Microsoft use in the native cmdlets.

The topic ‘Create a mandatory parameter if another parameter is chosen’ is closed to new replies.