无法处理错误 Powershell try with catch?
Unable to handle error Powershell try with catch?
Hi, I write some PowerShell cmd to get the attribute of TransportRule.
I know that this('TA') particular Transport rule does not exist in
the exchange, I handle that thing through try with a catch but I do
not get a correct result.
$temp="error"
Try{
Get-TransportRule -Identity TA|fl
}
Catch{
$temp
}
在 PowerShell window 中,您应该在单行中提供它,例如,
$temp="error"; Try{ Get-TransportRule -Identity TA|fl } Catch{ $temp }
另一种方法是,将其保存在扩展名为 .ps1 的文件中,如果您尝试 运行 从 powershell 中它会处理异常。
如果使用多行,命令将按顺序执行,每行将被视为一个separate command
。所以在你的图像中,它是逐行执行的,当涉及到 Get-TransportRule
命令时,它在 try 和 catch 之间没有任何联系,因为它是一个单独的命令。
希望对您有所帮助!干杯
问题是 Try / Catch 语句仅适用于终止错误。
你可以试试:
$temp="error"
Try{
Get-TransportRule -Identity TA -ErrorAction Stop | Format-List
}
Catch{
$temp
}
另一种选择是为当前会话更改它,设置默认变量 $ErrorActionPreference = 'Stop'
。那么就不需要使用-ErrorAction
参数了。
希望对您有所帮助。
Hi, I write some PowerShell cmd to get the attribute of TransportRule. I know that this('TA') particular Transport rule does not exist in the exchange, I handle that thing through try with a catch but I do not get a correct result.
$temp="error"
Try{
Get-TransportRule -Identity TA|fl
}
Catch{
$temp
}
在 PowerShell window 中,您应该在单行中提供它,例如,
$temp="error"; Try{ Get-TransportRule -Identity TA|fl } Catch{ $temp }
另一种方法是,将其保存在扩展名为 .ps1 的文件中,如果您尝试 运行 从 powershell 中它会处理异常。
如果使用多行,命令将按顺序执行,每行将被视为一个separate command
。所以在你的图像中,它是逐行执行的,当涉及到 Get-TransportRule
命令时,它在 try 和 catch 之间没有任何联系,因为它是一个单独的命令。
希望对您有所帮助!干杯
问题是 Try / Catch 语句仅适用于终止错误。 你可以试试:
$temp="error"
Try{
Get-TransportRule -Identity TA -ErrorAction Stop | Format-List
}
Catch{
$temp
}
另一种选择是为当前会话更改它,设置默认变量 $ErrorActionPreference = 'Stop'
。那么就不需要使用-ErrorAction
参数了。
希望对您有所帮助。