PowerShell错误处理核心机制

基础错误捕获结构

1
2
3
4
5
6
7
8
9
10
11
12
try {
Get-Content 'nonexistent.txt' -ErrorAction Stop
}
catch [System.IO.FileNotFoundException] {
Write-Host "文件未找到: $($_.Exception.Message)"
}
catch {
Write-Host "未知错误: $($_.Exception.GetType().FullName)"
}
finally {
# 清理资源代码
}

错误变量解析

1
2
3
4
# 自动变量应用示例
$Error[0] | Format-List * -Force
$Error.Clear()
$ErrorActionPreference = 'Continue'

自定义错误抛出

1
2
3
4
5
6
function Validate-Range {
param([int]$Value)
if ($Value -notin 1..100) {
throw [System.ArgumentOutOfRangeException]::new('Value')
}
}

最佳实践

  1. 优先使用强类型异常捕获
  2. 合理设置ErrorActionPreference
  3. 保持finally块简洁
  4. 记录完整错误堆栈信息
作者

吴波

发布于

2024-05-07

更新于

2025-03-25

许可协议

评论