【问题标题】:Powershell behaviour of [Switch]-Parameter [duplicate][Switch]-参数的Powershell行为[重复]
【发布时间】: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


【解决方案1】:

针对 [switch] 的参数绑定很棘手,因为仅仅在场-SwitchName 参数(之后没有显式参数值)就足够了 - PowerShell 看到 testswitch -foo $foo 并显示“用户指定 -foo present,然后他们给了我一些不相关的位置参数 $foo”。

要覆盖此行为,您可以将参数紧密绑定到带有冒号的开关参数:

testswitch -foo:$foo

...或者您可以splat the argument,PowerShell 将正确找出如何传递参数:

testswitch @PSBoundParameters

这两种方法都是“安全的”,例如。将显式参数与 : 紧密绑定适用于任何参数类型,不会改变任何行为(除了现在绑定的开关参数正确地)

【讨论】:

  • 不错,但请注意,命令有时可以区分不是指定-foo-foo:$false;常见的-Confirm 参数就是一个突出的例子。
猜你喜欢
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-12-11
  • 1970-01-01
  • 1970-01-01
  • 2021-12-30
  • 1970-01-01
相关资源
最近更新 更多