[英]Powershell behaviour of [Switch]-Parameter
我试图了解 -switch 参数的行为,尤其是在将它们传递给其他函数时。
我的基本问题是:我如何必须将开关参数的变量传递给另一个带有开关参数的 function,以便变量保持其值。 目前,看起来我总是将“true”传递给底层函数,只是因为传递了参数。
为了说明我的问题,我编写了这个测试脚本:
function testswitch{
param(
[switch]$foo
)
if ($foo -eq $true) {
"testswitch yes"
} else {
"testswitch no"
}
}
function testbool{
param(
[bool]$foo
)
if ($foo -eq $true) {
"testbool yes"
} else {
"testbool no"
}
}
function test{
param(
[switch]$foo
)
"received value:"
if ($foo -eq $true) {
"test yes"
} else {
"test no"
}
"passed calls:"
testswitch -foo $foo
testbool -foo $foo
"negated calls:"
testswitch -foo (!$foo)
testbool -foo (!$foo)
}
cls
test
"-----"
test -foo
"-----"
test -foo:$false
返回此 output:
received value:
test no
passed calls:
testswitch yes
testbool no
negated calls:
testswitch yes
testbool yes
-----
received value:
test yes
passed calls:
testswitch yes
testbool yes
negated calls:
testswitch yes
testbool no
-----
received value:
test no
passed calls:
testswitch yes
testbool no
negated calls:
testswitch yes
testbool yes
正如你所看到的,“testswitch”总是返回“yes”——这不是我想要的。 不幸的是,在谷歌上很难找到关于 switch 参数的体面信息,因为还有一个条件语句,它根据我能想出的关键字获得了很多点击。
针对[switch]
的参数绑定很棘手,因为仅存在-SwitchName
参数(之后没有显式参数值)就足够了 - PowerShell 参见testswitch -foo $foo
并转到“用户指定-foo
存在,然后他们给了我一些不相关的位置参数$foo
"。
要覆盖此行为,您可以使用冒号将参数紧密绑定到 switch 参数:
testswitch -foo:$foo
...或者您可以喷出参数,PowerShell 将正确计算出如何通过 arguments:
testswitch @PSBoundParameters
这两种方法都是“安全的”,例如。 将显式 arguments 紧密结合:
适用于任何参数类型不会改变任何行为(除了开关 arguments 现在被正确绑定)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.