如何在 PowerShell 中通过 splatting 将开关参数作为变量传递?

2024-01-02

如果您有多个参数在调用命令或脚本时需要一个值,我知道您可以像这样传递它:

$parameters = @{
    name = "John"
    last_name = "Doe"
}

但如果命令或脚本实际上只是期望-T指示类似标志的内容,但参数本身不需要值。我如何将其设置在变量中?

$optionalT = ""
if ($itNeedsTheT) $optionalT = "-T"

command $optionalT

如果我这样做,它会抱怨以下消息:

Unknown argument 'T' on command line.

tl;dr

# Pass the $itNeedsT Boolean - which indicates whether the -T switch should
# be passed - as the switch's *value*.
command -T:$itNeedsTheT  

If $itNeedsTheT is $false, 与上面相同omitting -T - usually(请继续阅读以了解详细信息)。

使用时需要注意:将开关名称与值分开。


As boxdog https://stackoverflow.com/users/9529842/boxdog在评论中指出,在与使用的哈希表中飞溅(@parameters) https://stackoverflow.com/a/51219535/45375, you use a Boolean表示开关参数的值(类似标志的参数类型[switch]) .

# Dynamically determine if -Recurse should be turned on.
$recurseIfTrue = $true

# Define the hashtable for splatting...
$parameters = @{
  Path = '.'
  Recurse = $recurseIfTrue  # turn the -Recurse switch on or off
}

# ... and pass it to the target command.
# *Loosely speaking*, the following command is the same as either:
#   Get-ChildItem -Path '.' -Recurse  # if $recuseIfTrue was $true
# or:
#   Get-ChildItem -Path '.'           # if $recuseIfTrue was $false
Get-ChildItem @parameters

也就是说,宽松地说:

  • use $true to pass开关
  • use $false to not通过开关。

这允许您保留无条件包含 switch 参数的单个哈希表定义,但其值可以通过编程方式确定。

Caveat:

严格来说,哈希表条目Recurse = $true翻译为参数-Recurse:$true and Recurse = $false不翻译成omitting参数,它转化为传递-Recurse:$false.

In most cases, omitting一个开关-Foo并传递它的值$false - i.e. -Foo:$false - are 相等的.

但是,命令can检测差异,有时采取不同的行动:

一个值得注意的例子是-Confirm常用(开关)参数:omitting -Confirm意味着$ConfirmPreference偏好变量受到尊重,而-Confirm:$false意味着偏好变量应该是被覆盖(并且确认应该not应要求)。

如果您想自己在 PowerShell 脚本或函数中进行这种区分,您可以调用$PSBoundParameters.ContainsKey('Foo')除了检查$Foo (-Foo) 切换参数变量的值。

如果您正在处理这样的命令并且想要以编程方式强制执行omission一个开关参数,你别无选择,只能有条件的在单独的步骤中为此开关添加一个条目:

# Dynamically determine if -Recurse should be turned on.
$recurseIfTrue = $true

# A 'Recurse' key now can NOT be included unconditionally,
# if you want to *omit* -Recurse in case $recurseIfTrue is $false
$parameters = @{
  Path = '.'
}

# Add a 'Recurse' entry only if the switch should be passed.
if ($recurseIfTrue) {
  $parameters.Recurse = $true
}

Get-ChildItem @parameters

最后,请注意,作为通过 splatting 以编程方式指定开关值的替代方法,您可以直接将动态值传递给开关:

# Dynamically determine if -Recurse should be turned on.
$recurseIfTrue = $true

Get-ChildItem -Path . -Recurse:$recurseIfTrue

请注意需要使用:将开关名称与其值分开.

这是必要的,因为使用习惯空白将参数名称与其值分开将导致 PowerShell 将布尔值解释为next参数,考虑到 switch 参数通常不采用values.

虽然很少使用,但这:- 基于语法适用于all参数类型。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何在 PowerShell 中通过 splatting 将开关参数作为变量传递? 的相关文章

随机推荐