PowerShell脚本在程序失败时停止(类似于bash的`set -o errexit`)。

4
有没有一种优雅的PowerShell脚本设置,如果程序失败,就会退出正在运行的PowerShell脚本(或shell实例)?
我想象中的是类似于Bash功能set -o errexit(或set -e),但适用于PowerShell。在这个功能中,如果bash脚本中的程序失败(进程返回代码不是0),则bash shell实例立即退出。
在PowerShell中,脚本可以明确检查$LastExitCode$?if($?){exit})。然而,对于每个程序调用来说,这样做变得很麻烦。也许PowerShell有一个自动检查和响应程序返回代码的功能?

在脚本中解释

使用虚构的习语Set-Powershell-Auto-Exit
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

你不能把代码放在Try Catch块中,然后简单地退出吗? - Mark Kram
@MarkKram,使用try ... catch需要很多行代码。我正在寻找一条语句来设置PowerShell脚本模式,类似于bash的set -e - JamesThomasMoon
2个回答

10
很遗憾,从PowerShell (Core) 7.3.x开始,PowerShell没有提供任何自动退出脚本的方式,当外部程序报告非零的退出代码时。
然而,正如Daniel T的回答中首次提到的那样,在v7.3和v7.4预览版本中有一个实验性功能,PSNativeCommandErrorActionPreference可用,如果将$PSNativeCommandArgumentPassing偏好变量设置为$true,则会对外部程序的非零退出代码发出PowerShell错误响应,因此受到$ErrorActionPreference偏好变量的影响;注意

仅适用于PowerShell本地命令(cmdlets、脚本、函数),可以使用$ErrorActionPreference = 'Stop',这将导致退出代码为1

  • 如果您需要更多控制报告的退出代码,请参阅this answer

  • 有关PowerShell如何向外界报告退出代码的概述,请参阅this answer

对于外部程序,您必须显式地测试$LASTEXITCODE -eq 0并根据此采取行动,但作为解决方法,您可以在所有外部程序调用中使用一个辅助函数,如this answer所示。


1
很高兴听到它对你有用,@JamesThomasMoon1979;我很乐意。 - mklement0

2
截至 PowerShell 7.3.0 预览版,已经有一个实验性的实现来在外部程序失败时退出脚本。新的 RFC PR 已经移动到另一个链接
# Global config setup
Enable-ExperimentalFeature PSNativeCommandErrorActionPreference
exit

# Per-script setup
$ErrorActionPreference = 'Stop'
$PSNativeCommandUseErrorActionPreference = $true

# Code from original question
& {
    & program.exe --fail  # this program fails with an error code
    & foo.exe             # this never runs because script has exited
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接