【问题标题】:Unable to handle error Powershell try with catch?无法处理错误 Powershell 尝试使用 catch 吗?
【发布时间】:2019-09-18 15:59:30
【问题描述】:

您好,我编写了一些 PowerShell cmd 来获取 TransportRule 的属性。 我知道这个('TA')特定的传输规则不存在 exchange,我通过 try with a catch 来处理这件事,但我做到了 没有得到正确的结果。

$temp="error"
Try{
Get-TransportRule -Identity TA|fl
}
Catch{
$temp
}

【问题讨论】:

  • 编辑问题。将您的代码和错误消息添加为文本,而不是图像。图片很难阅读,无法搜索,复制任何代码都需要额外的努力。更重要的是,解释所需的输出是什么。

标签: powershell exchange-server


【解决方案1】:

问题是 Try / Catch 语句仅适用于终止错误。 你可以试试:

$temp="error"
Try{ 
    Get-TransportRule -Identity TA -ErrorAction Stop | Format-List 
} 
Catch{ 
    $temp
}

另一个选项是为当前会话更改它,设置默认变量$ErrorActionPreference = 'Stop'。那么您不需要使用-ErrorAction 参数。

希望对您有所帮助。

【讨论】:

    【解决方案2】:

    在 PowerShell 窗口中,您应该在单行中给出它,例如,

    $temp="error"; Try{ Get-TransportRule -Identity TA|fl } Catch{ $temp }
    

    另一种方法是将其保存在扩展名为 .ps1 的文件中,如果您尝试从 powershell 运行它,它将处理异常。

    如果使用多行,命令将按顺序执行,每一行将被视为separate command。所以在你的图像中,它是逐行执行的,当涉及到 Get-TransportRule 命令时,它在 try 和 catch 之间没有任何联系,因为它是一个单独的命令。

    希望对您有所帮助!干杯

    【讨论】:

    • 请编辑答案并解释为什么单行而不是使用多行。
    猜你喜欢
    • 1970-01-01
    • 2016-03-10
    • 1970-01-01
    • 2012-04-20
    • 1970-01-01
    • 1970-01-01
    • 2014-01-01
    • 1970-01-01
    • 2022-01-05
    相关资源
    最近更新 更多