如何在 Powershell 中将开关参数标记为强制
我很确定除了我发现的之外我没有任何其他选择,但我想选择集体的互联网大脑。
在将布尔值传递给自定义函数时,我更喜欢使用 [switch] 参数。但是,在某些情况下,我想将 switch 参数标记为强制参数。这可以选择通过参数上的[parameter(Mandatory = $true)] 来完成。但是,我真的不喜欢出现的 UI 提示。我更喜欢抛出异常。
但是,开关可以是 true 或 false,并且“IsPresent”属性没有区别。如果我将开关参数作为 -example:$false 传递,则开关会报告 $example.IsPresent 为 false!
我已经求助于使用[bool]。例如:
param
(
[bool]$theValue = $(throw('You didn't specify the value!'))
);
我还有其他的技巧吗?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在某种程度上,
switch
参数始终是必需的。如果您不指定它,它将获得 false 值。如果您指定它 (-var
),它会获取值 true,如果您也指定该值 (-var:$false
),它会获取指定的值。我真的无法想象强制指定开关的情况。如果不指定,则为 false。就这么简单。
我想你想要的是具体提及参数的值是 true 还是 false?如果是这种情况,您提到的
bool
版本就是我想要的,尽管它与switch
的工作方式也相同:并且还涉及
$ example.IsPresent
- 我知道它不直观 /broken ,但它与 switch 变量本身的值相同。这就是Switch Paramater
的构造函数的定义方式,它唯一的属性是IsPresent
:http:// /msdn.microsoft.com/en-us/library/system.management.automation.switchparameter.ctor%28v=vs.85%29.aspx
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 withswitch
too: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 forSwitch Paramater
is defined and the only property that it has is theIsPresent
:http://msdn.microsoft.com/en-us/library/system.management.automation.switchparameter.ctor%28v=vs.85%29.aspx