约 2266 字

约 11 分钟

#错误处理

#简介

PowerShell 中的错误分为终止性错误和非终止性错误。终止性错误会中断当前语句,非终止性错误会写入错误流但继续执行。理解两者的区别是正确使用 try/catch 的前提。

#错误类型

  • 终止性错误:例如语法错误、throw 抛出的错误,会中断执行。
  • 非终止性错误:例如某个文件不存在,命令报告错误后仍会继续处理其他对象。

很多 cmdlet 可以通过 -ErrorAction Stop 把非终止性错误提升为终止性错误。

#try / catch / finally

使用 try 捕获终止性错误:

try {
    Get-Content ./missing.txt -ErrorAction Stop
}
catch {
    Write-Output "捕获到错误:$($_.Exception.Message)"
}
finally {
    Write-Output "无论成功与否都会执行"
}
  • catch 中 $_ 表示当前错误对象。
  • finally 块总会执行,常用于清理资源。
  • 可以写多个 catch 按异常类型分别处理:
try {
    [int]"abc"
}
catch [System.FormatException] {
    "格式错误"
}
catch {
    "其他错误"
}

#throw

使用 throw 主动抛出一个终止性错误:

function Test-Value {
    param($Value)
    if ($null -eq $Value) {
        throw "Value 不能为空"
    }
    $Value
}

Test-Value -Value $null

也可以在 catch 中重新抛出当前错误:

catch {
    Write-Output "记录日志"
    throw
}

#错误相关变量

变量说明
$Error最近的错误对象集合,$Error[0] 是最新的一条
$?上一条命令是否成功
$LASTEXITCODE上一个外部程序的退出码
> Get-Item ./missing.txt
> $?
False
> $Error[0].Exception.Message

#ErrorAction 与 ErrorActionPreference

-ErrorAction 是通用参数,用于控制单个命令的错误行为:

Get-ChildItem ./missing -ErrorAction SilentlyContinue
Get-ChildItem ./missing -ErrorAction Stop

$ErrorActionPreference 设置当前作用域的默认行为:

$ErrorActionPreference = "Stop"

常用取值:

值说明
Continue显示错误并继续,默认值
Stop将错误视为终止性错误
SilentlyContinue不显示错误并继续
Ignore忽略错误并继续
Inquire提示用户如何处理

#trap 简介

trap 是较早期的错误处理方式,用于捕获当前作用域中的终止性错误:

trap {
    Write-Output "发生错误:$($_.Exception.Message)"
    continue
}

throw "示例错误"

trap 中的 continue 表示处理错误后继续执行,break 表示停止当前作用域。新代码通常推荐使用 try/catch。

#推荐阅读

更新: 2026/11/2

作者: planc

创建: 2026/11/2