Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mark a switch parameter as mandatory in Powershell

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?

like image 280
Johnny Kauffman Avatar asked Aug 29 '11 19:08

Johnny Kauffman


1 Answers

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

like image 63
manojlds Avatar answered Nov 08 '22 19:11

manojlds