Author Posts

June 17, 2013 at 6:07 am

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

June 17, 2013 at 6:09 am

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.

June 17, 2013 at 6:14 am

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

June 17, 2013 at 6:22 am

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

June 17, 2013 at 6:22 am

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.