[SOLVED]Enabling a script parameter only when another parameter is used?

This topic contains 4 replies, has 3 voices, and was last updated by  Poshoholic 5 years ago.

  • Author
  • #7563

    John Mello

    I'm trying to create a script that will email the results of the script by using a switch parameter called EmailReport. When this switch is set I want to make another parameter called EmailTo mandatory. I tired doint this with Parameter sets but I can't seem to get it work, it's either always mandatory or not. Anyone notice if I’m missing something in the following code?

    HelpMessage="Active Diretory samAccountName(s) to work SIP enable")]
    HelpMessage="Use to deliver an HTML report of all actions")]
    HelpMessage="Enter an email address to send an HTML report to")]
  • #7564

    Don Jones

    I'm gonna have to ask you to NOT paste in from Microsoft word ;). Want to edit that message and try again? Paste into Notepad first to strip all the Word nonsense, if needed.

  • #7568

    John Mello

    Sorry :), I realized after I posted it and was in the process of cleaning it up

  • #7571

    Don Jones

    In terms of staying consistent with PowerShell, you'd only use your -EmailTo parameter. Use $PSBoundParameters to check and see if it's specified; if it is, you e-mail; if it isn't, you don't. PowerShell doesn't really promulgate the idea of using one switch to 'turn on' a bunch of others.

    To do exactly what you want, you'd need another named parameter set, and you'd need to specify that as the default set in CmdletBinding(). Right now, you only have one parameter set – which is why it's always coming up as mandatory. -Identity doesn't "count" as a parameter set because it's in all parameter sets (since it isn't assigned to one explicitly).

  • #7572


    Have you thought about renaming EmailHTMLReport as EmailHTMLReportTo, changing its type to string[], and then just using that as a mandatory parameter in the parameter set where this matters? That might be a better approach.

    You're right that mandatory is either there or it isn't. You shouldn't have to dynamically change it on the fly...it's more of a cmdlet parameter design problem, in which case you simply need to lay out the parameters differently so that it makes sense. Note that you can have a parameter that is mandatory for one parameter set and non-mandatory for another by simply specifying the parameter attributes once for each parameter set.

  • #7580

    John Mello

    Thanks to DonJ for clearing up the idea of Parameter sets for me and Poshoholic/DonJ for the KISS suggestion.

You must be logged in to reply to this topic.