首页/系统/Windows 运维速查/错误处理偏好 $ErrorActionPreference
PowerShell 基础66 条

错误处理偏好 $ErrorActionPreference

全局或局部控制错误行为:默认 Continue 继续执行,脚本里常设 Stop 让错误立即中断,避免带病运行。

Windows 运维速查系统更新于 2026-10-12
用途统一错误响应策略
语法$ErrorActionPreference = 'Stop';-ErrorAction 逐命令覆盖
取值Continue(默认)、Stop、SilentlyContinue、Inquire、Ignore

常用示例

常用示例
$ErrorActionPreference = 'Stop'
try { Get-Item D:\nope } catch { $_.Exception.Message }
Get-ChildItem D:\nope2 -ErrorAction Continue
Stop 让非终止错误变成可捕获的终止错误,这是 try/catch 能兜住一切的前提。

易错点

  • 默认 Continue 下脚本会“报错继续跑”,漏检导致结果不完整
  • Stop 在小段调试时更友好,但交互会话里设置会影响后续所有命令

数据来源与参考

  • Microsoft Learn:about_Preference_Variables

相关工具

​‌‌​​‌​​​‌‌​‌‌‌‌​‌‌​​​‌‌​‌‌‌​​‌‌​​‌​‌‌‌​​‌‌‌​​​‌​‌‌​‌​​‌​‌‌‌​​​‌​‌‌​‌​​‌​‌‌​​​‌‌​‌‌‌​‌​​​‌‌​‌‌‌‌​​‌​‌‌‌​​‌‌​​​‌‌​‌‌​‌‌‌‌​‌‌​‌‌​‌