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

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?

[CmdletBinding()]

Param(Â Â Â 

[Parameter(Mandatory=$True,
Position=0,
ValueFromPipeline=$true,
ValueFromPipelineByPropertyName=$True,
HelpMessage="Active Diretory samAccountName(s) to work SIP enable")]
[String[]]$Identity,

[Parameter(ParameterSetName="EmailReport",
Mandatory=$False,
HelpMessage="Use to deliver an HTML report of all actions")]
[switch]$EmailHTMLReport,

[Parameter(ParameterSetName="EmailReport",
Mandatory=$TRUE,
HelpMessage="Enter an email address to send an HTML report to")]
[String[]]$emailTo

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.

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

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).

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.

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