trap [Exception] {
'在 trap 中捕捉到腳本異常'
$_.Exception.Message
continue
}
.\test.ps1 # 內容: Get-NonExistentCommand
輸出:在 trap 中捕捉到腳本異常 / The term 'Get-NonExistentCommand' is not recognized...
# test.ps1 內容: dir D:\NonExistentPath
# 運行結果: 直接報錯紅字,trap 未觸發
trap [Exception] {
'在 trap 中捕捉到腳本異常'
$_.Exception.Message
continue
}
$ErrorActionPreference = 'Stop'
.\test.ps1 # 內容: dir D:\NonExistentPath
輸出:在 trap 中捕捉到腳本異常 / Cannot find path 'D:\NonExistentPath' because it does not exist.
try {
dir D:\NonExistentPath -ErrorAction Stop
} catch {
'在 catch 中捕捉到異常'
$_.Exception.Message
}
$ErrorActionPreference = 'Stop' 統一將非終止錯誤提升為終止錯誤,便於集中捕捉。-ErrorAction Stop。trap 處理全局未捕獲異常,try/catch/finally 處理局部邏輯錯誤。continue 在 trap 中表示繼續執行下一條語句;break 表示退出當前作用域。