【问题标题】:How to add -confirm:$false in a powershell hashtable?如何在 powershell 哈希表中添加 -confirm:$false?
【发布时间】:2021-10-20 05:37:05
【问题描述】:
$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

如何在Hashtable中添加这个$false?

【问题讨论】:

    标签: powershell exchange-server


    【解决方案1】:

    更改 $arguments 哈希表:

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

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

    【讨论】:

    • 我试过了,但这不起作用。它导致 -Confirm False 不适用于 disable-remotemailbox 命令。也许确认可以以某种方式全局禁用?
    • @insane_IT 将 '-{0} {1} ' 更改为 '-{0}:{1} '
    • 变量 $command_args 仅用于以人类可读格式打印命令。我之前尝试过 & $cmdlet $command_args 但这也不起作用。传递哈希表变量是唯一可以正常工作的方法,除了需要 -confirm:$false 标志的 cmdlet。
    • @insane_IT 我觉得我必须在这里遗漏一些东西 - 当你抛出一个包含 @{Confirm=$false} 条目的哈希表时,你收到的确切错误消息是什么?
    • 奇怪的是我根本没有输出
    【解决方案2】:

    添加到Mathias's concise answer

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

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

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

    如果我指定一个名为$Delete的开关参数

    Param( [Switch]$Delete )
    

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

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

    当然,您可以缩短为:

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

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

    【讨论】:

      猜你喜欢
      • 2021-10-21
      • 1970-01-01
      • 2021-04-04
      • 2012-02-06
      • 2021-01-22
      • 2018-11-21
      • 2019-10-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多