简体   繁体   English

如何在Powershell中将switch参数标记为必需

[英]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. 在将布尔值传递给自定义函数时,我更喜欢使用[switch]参数。 However, I have a few cases in which I wanted to mark the switch parameter as mandatory. 但是,我有几种情况需要将switch参数标记为必需。 This can optionally be accomplished through [parameter(Mandatory = $true)] on the parameter. 这可以通过参数的[parameter(Mandatory = $ true)]选择性地完成。 However, I really dislike the UI prompt that shows up. 但是,我真的不喜欢出现的UI提示。 I much prefer throwing an exception. 我更喜欢抛出异常。

But, a switch can be either true or false, and the "IsPresent" property makes no distinction. 但是,一个开关可以是true或false,而“IsPresent”属性没有区别。 If I pass a switch parameter as -example:$false , the switch reports that $example.IsPresent is false ! 如果我将switch参数传递为-example:$ false ,则交换机报告$ example.IsPresent为false

I have resorted to using a [bool]. 我已经使用了[bool]。 For example: 例如:

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

Are there any other tricks I can pull? 我还有其他技巧吗?

In a way a switch parameter is always mandatory. 在某种程度上, switch参数始终是必需的。 If you don't specify it, it gets a value of false. 如果未指定它,则其值为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. 如果指定它( -var ),则获取值true,如果指定值( -var:$false ),则获取指定的值。

I can't really think of a situation where it is mandatory to specify a switch. 我真的不能想到必须指定一个开关的情况。 If you don't specify, it is false. 如果您未指定,则为false。 Simple as that. 就那么简单。

I think what you want is to specifically mention the value of the param to be true or false? 我想你想要的是具体提到param的价值是真还是假? 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: 如果是这种情况,你提到的bool版本就是我想要的,尽管它也与switch一样:

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. 还有关于$example.IsPresent - 我知道它不直观/坏,但它与switch变量本身的值相同。 That is how the constructor for Switch Paramater is defined and the only property that it has is the IsPresent : 这就是如何定义Switch Paramater的构造函数,它唯一的属性是IsPresent

Creates a new SwitchParameter object that includes a Boolean value that identifies whether the switch is present. 创建一个新的SwitchParameter对象,该对象包含一个布尔值,用于标识交换机是否存在。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM