8

I'm pretty sure I don't have any other options other than what I've uncovered, but I wanted to pick the collective internet brain.

I prefer to use a [switch] parameter when passing boolean values to custom functions. However, I have a few cases in which I wanted to mark the switch parameter as mandatory. This can optionally be accomplished through [parameter(Mandatory = $true)] on the parameter. However, I really dislike the UI prompt that shows up. I much prefer throwing an exception.

But, a switch can be either true or false, and the "IsPresent" property makes no distinction. If I pass a switch parameter as -example:$false, the switch reports that $example.IsPresent is false!

I have resorted to using a [bool]. For example:

param
(
   [bool]$theValue = $(throw('You didn't specify the value!'))
);

Are there any other tricks I can pull?

1
  • Why not have two switches? example and exampleOff. Then, when neither IsPresent throw an error. Commented Mar 7, 2017 at 16:52

1 Answer 1

22

In a way a switch parameter is always mandatory. If you don't specify it, it gets a value of false. If you specify it ( -var) it gets a value true and if you specify the value too (-var:$false) it gets the value specified.

I can't really think of a situation where it is mandatory to specify a switch. If you don't specify, it is false. Simple as that.

I think what you want is to specifically mention the value of the param to be true or false? If that is the case, the bool version that you mention is what I would go for, though it works the same way with switch too:

param([switch]$a  = $(throw "You didn't specify the value"))

And also regarding $example.IsPresent - I know it is not intuitive /broken , but it is the same as the value of the switch variable itself. That is how the constructor for Switch Paramater is defined and the only property that it has is the IsPresent:

Creates a new SwitchParameter object that includes a Boolean value that identifies whether the switch is present.

http://msdn.microsoft.com/en-us/library/system.management.automation.switchparameter.ctor%28v=vs.85%29.aspx

Sign up to request clarification or add additional context in comments.

2 Comments

If the exception message is what's bothering you, this is the best you're going to get.
Oops! I had incorrectly concluded that throwing the error when using "Switch" in the parameter list would not work. I have tried this again, and it seems good to go. manojlds's answer is both accurate and very well detailed.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.