【发布时间】:2022-11-23 04:32:10
【问题描述】:
我试图了解 -switch 参数的行为,尤其是在将它们传递给其他函数时。
我的基本问题是:如何将 switch 参数的变量传递给另一个带有 switch 参数的函数,以便变量保持其值。目前,看起来我总是将“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
返回此输出:
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”总是返回“是”——这不是我想要的。 不幸的是,很难在谷歌上找到关于 switch 参数的准确信息,因为还有条件语句根据我能想到的关键字获得了很多点击。
【问题讨论】:
-
将
-foo $foo更改为-foo:$foo -
哇,这很容易解决!谢谢你。 - 何时使用 -foo:$foo 而不是 -foo $foo 的任何解释?常规变量不需要那个 afaik。
-
-foo:$foo将始终有效,但仅对[switch]'es 是绝对必要的
标签: powershell parameter-passing switch-parameter