如果程序失败,powershell脚本将停止(例如bash`set -o errexit`) [英] powershell script stops if program fails (like bash `set -o errexit`)
问题描述
是否存在一个优雅的Powershell脚本设置,如果程序失败,该设置将退出正在运行的Powershell脚本(或Shell实例)?
我正在想像Bash功能,例如Powershell的 set -o errexit
(或 set -e
).在该功能中,如果bash脚本中的程序失败(进程返回码不是 0
),则bash shell实例将立即退出.
I'm imagining something like Bash feature set -o errexit
(or set -e
) but for Powershell. In that feature, if a program in the bash script fails (process return code was not 0
) then the bash shell instance immediately exits.
在powershell中,脚本可以检查 $ LastExitCode
.但是,对于每个程序调用而言,这样做变得很麻烦.也许powershell具有自动检查程序返回代码并对之进行响应的功能.
In powershell, the script could check $LastExitCode
. However, that becomes cumbersome to do for every program call. Maybe powershell has a feature to automatically check and react to program return codes.
Set-Powershell-Auto-Exit 'ProgramReturnCode' # what should this be?
& program.exe --fail # this program fails with an error code
& foo.exe # this never runs because script has exited
推荐答案
不幸的是,从PowerShell Core 7.0.0-preview.3开始,PowerShell提供了 no 方法来自动退出脚本当外部程序报告非零退出代码时.
Unfortunately, as of PowerShell Core 7.0.0-preview.3, PowerShell offers no way to automatically exit a script when an external program reports a nonzero exit code.
-
正在此中讨论添加支持RFC提案.
对于 PowerShell-native 命令(仅 )(cmdlet,脚本,函数),可以使用 $ ErrorActionPreference ='Stop'
,这会导致退出代码 1
.
For PowerShell-native commands only (cmdlets, scripts, functions), $ErrorActionPreference = 'Stop'
can be used, which results in exit code 1
.
就目前而言,您必须明确测试 $ LASTEXITCODE -eq 0
,并以此为基础采取措施解决方法,您可以对所有外部程序调用使用 helper函数 ,如
For now, you must test for $LASTEXITCODE -eq 0
explicitly and take action based on that, but as a workaround you can use a helper function for all external-program invocations, as shown in this answer.
这篇关于如果程序失败,powershell脚本将停止(例如bash`set -o errexit`)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!