如何在 powershell 哈希表中添加 -confirm:$false?

How to add -confirm:$false in a powershell hashtable?

$cmdlet="Disable-RemoteMailBox"
$arguments = @{Identity=$identity;DomainController=$domaincontroller;Archive=""}
$command_args=""
$arguments.keys | ForEach-Object{
    $message = '-{0} {1} ' -f $_, $arguments[$_]
        $command_args+= $message
}
$result=& $cmdlet @arguments 2>&1

最后这样执行:

Disable-RemoteMailBox -Identity abc@corp.com -DomainController dc.corp.local -Archive 

但我需要添加一个确认:$false

Disable-RemoteMailBox -Identity abc@corp.com -DomainController dc.corp.local -Archive -Confirm:$false

如何在哈希表中添加这个$false?

$arguments 哈希表更改为:

$arguments = @{Identity=$identity;DomainController=$domaincontroller;Archive=""}

$arguments = @{Identity=$identity;DomainController=$domaincontroller;Archive="";Confirm=$false}

添加到

除了确认功能与 $ConfirmPreference 首选项变量的集成外,-Confirm 公共参数可以看作是一个简单的开关参数。它存在或不存在。但是,PowerShell 的内部类型转换引擎将评估 [Switch] 更像 [Boolean] 如果将 [Bool] 转换为 [Switch],您可以看到这一点。

[Switch]$true[Switch]$false 将分别 return IsPresent True/False。

如果您在 splatting hash table 中指定 Confirm = $false,参数绑定期间发生的类型强制转换(转换)将正确处理它。对于任何其他开关参数也是如此,甚至是您在自定义函数中定义的自定义参数。当您需要评估函数内部的开关参数时,这种类型转换也很明显。

如果我指定一个名为 $Delete

的开关参数
Param( [Switch]$Delete )

然后我可以在内部执行如下逻辑:

If( $Delete -eq $true ) {
    # Delete the file or whatever...
}

当然可以缩短为:

If( $Delete ) {
    # Delete the file or whatever...
}

但是,您无需深入了解 PowerShell 的类型转换系统即可在 splatting hash table 中使用 Boolean 或 Switch 参数。它记录在 about_Splatting 中。前几行将解释开关参数的散列 table splatting。