首页 > 解决方案 > 从 Powershell 中的 TRAP 中排除错误代码

问题描述

我正在运行一个脚本来获取我正在监视的某些站点的 Invoke-WebRequest 状态代码(例如 504、400、200 等)。

我正在使用 TRAP 方法将错误记录到一个文本文件中,以便以后进行分析。

代码如下:

Trap
{
write-host ("An error has occurred: "+$_.exception.message)
Write-Host ("Please see error message or log file")
$_.Exception.Message+" "+(Get-Date) | Out-File -Append "$PSScriptRoot\log.txt"
$_.Exception.InnerException.Message | Out-File -Append "$PSScriptRoot\log.txt"
$site                               | Out-File -Append "$PSScriptRoot\log.txt"
"---------------------------------" | Out-File -Append "$PSScriptRoot\log.txt"
}

问题:我可以排除捕获某些错误代码,如“503”吗?

标签: powershellerror-handlingpowershell-trap

解决方案


不幸的是,看起来陷阱语句无法过滤或限制,因为 TRAP 始终适用于整个 SCOPE。

但是您可以做的是将 error_type 拆分为几个 TRAPS,例如:

"trap [[error_type]] {statement_list}"

推荐阅读