为何PowerShell中Set-Location命令的错误无法被try/catch捕获?
为什么Set-Location的错误无法被try/catch捕获?
PowerShell的错误分为终止错误和非终止错误两类,只有终止错误会触发try/catch块执行。而Set-Location在目标路径不存在时,默认抛出的是非终止错误,所以不会被catch代码块捕获。
要让这类错误能被try/catch处理,有两种常用方式:
给命令添加
-ErrorAction Stop参数,强制将非终止错误转为终止错误
修改后的代码示例:try { Set-Location "c:\non-existing-path" -ErrorAction Stop } catch { Write-Host "cannot find path" }全局设置错误偏好变量
$ErrorActionPreference为Stop,该设置会让当前会话中所有非终止错误都转为终止错误
代码示例:$ErrorActionPreference = "Stop" try { Set-Location "c:\non-existing-path" } catch { Write-Host "cannot find path" }
内容的提问来源于stack exchange,提问作者user310291
相关产品推荐
相关产品推荐

