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参数类型。