Can parameters be mandatory based on value of other parameters?


I’m trying to figure out if it’s possible and how to require parameter only if other parameter is used. For example I want to have my script to have paramater called “DebugRun”, if that parameter is set to $True then I want users to also enter “DebugEmail” parameter as well (becomes mandatory). If “DebugRun” on the other hand is not specified then both parameters are optional.
How can this be accomplished? That’s what I have right now




Have you tried using parameter sets

Well, yes and no.

If you’re remaining consistent with the shell’s usual practices, then you’d only provide $DebugEmail. If it is specified, then you’re debugging. If not, then you’re not. There isn’t really a need for $DebugRun.

However, you could achieve what you’re after, I think. You’d specify $DebugRun as a [switch] parameter. That way, PowerShell will make it $True if the script is run with -DebugRun, and $False if not. Designate it as being in a parameter set named, for example, “DebugRun”. Add $DebugEmail to the same parameter set, and mark it as mandatory. That way, if -DebugRun is specified, you’re “in” the DebugRun parameter set, and -DebugEmail becomes mandatory. But this won’t stop someone from specifying just -DebugEmail and not specifying -DebugRun. PowerShell doesn’t have many places I can think of where you use one parameter to ‘turn on’ another one.

BTW, for something like -DebugRun, it’s more common to specify it as a [switch] than as [bool]. For example, you don’t see “-Force $True” all that often, right? You just see “-Force” used, or not used. That’s a switch.

It’s easy enough to just have -DebugEmail, though.

If ($PSBoundParameters.ContainsKey(‘DebugEmail’) {

you’re debugging

} else P

you’re not


That would eliminate the need for -DebugRun, and I think be more consistent with the rest of the shell.

Personally, in this case I’d get rid of the DebugRun parameter and just use the DebugEmail parameter, since you’re tying them together anyway. Instead of requiring the user to both enter a boolean / switch value for DebugRun and a string value for DebugEmail, the user can just optionally enter the string parameter. If it’s set to something, your function can act as though the old $DebugRun parameter was set:

param (

$DebugRun = -not [string]::IsNullOrEmpty($DebugEmail)

To answer your question, though, you can’t define that sort of dependency on the ‘value’ of another parameter in the param block, but you can write some validation code in the function (typically in the Begin block) to accomplish it. Using parameter sets, you can do something similar, but it’s based on the ‘presence’ of the other parameter (not its actual value.)