You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何PowerShell中Set-Location命令的错误无法被try/catch捕获?

为什么Set-Location的错误无法被try/catch捕获?

PowerShell的错误分为终止错误和非终止错误两类,只有终止错误会触发try/catch块执行。而Set-Location在目标路径不存在时,默认抛出的是非终止错误,所以不会被catch代码块捕获。

要让这类错误能被try/catch处理,有两种常用方式:

  1. 给命令添加-ErrorAction Stop参数,强制将非终止错误转为终止错误
    修改后的代码示例:

    try {
      Set-Location "c:\non-existing-path" -ErrorAction Stop
    } catch {
      Write-Host "cannot find path"
    }
    
  2. 全局设置错误偏好变量$ErrorActionPreference为Stop,该设置会让当前会话中所有非终止错误都转为终止错误
    代码示例:

    $ErrorActionPreference = "Stop"
    try {
      Set-Location "c:\non-existing-path"
    } catch {
      Write-Host "cannot find path"
    }
    

内容的提问来源于stack exchange,提问作者user310291

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.23 13:48:23