为什么在使用调用运算符和$ErrorActionPerference = "Stop"
时使用非零退出代码时,PowerShell脚本不会结束?
使用以下示例,我得到结果managed to get here with exit code 1
:
$ErrorActionPreference = "Stop"
& cmd.exe /c "exit 1"
Write-Host "managed to get here with exit code $LASTEXITCODE"
Microsoft documentation for the call operator没有讨论使用call运算符时会发生什么,它只说明以下内容:
运行命令,脚本或脚本块。调用运算符,也称为"调用运算符,"允许您运行存储在变量中并由字符串表示的命令。因为调用操作符不解析命令,所以它无法解释命令参数。
此外,如果这是预期的行为,是否还有其他方法让调用操作符导致错误而不是让它继续?
答案 0 :(得分:5)
返回代码不是 PowerShell 错误 - 它与任何其他变量的看法相同。
您需要使用PowerShell对变量进行操作并throw
出错,以便将脚本视为终止错误:
$ErrorActionPreference = "Stop"
& cmd.exe /c "exit 1"
if ($LASTEXITCODE -ne 0) { throw "Exit code is $LASTEXITCODE" }
答案 1 :(得分:1)
在几乎所有的PowerShell脚本中,我都倾向于“快速失败”,因此我几乎总是有一个看起来像这样的小函数:
function Invoke-NativeCommand() {
# A handy way to run a command, and automatically throw an error if the
# exit code is non-zero.
if ($args.Count -eq 0) {
throw "Must supply some arguments."
}
$command = $args[0]
$commandArgs = @()
if ($args.Count -gt 1) {
$commandArgs = $args[1..($args.Count - 1)]
}
& $command $commandArgs
$result = $LASTEXITCODE
if ($result -ne 0) {
throw "$command $commandArgs exited with code $result."
}
}
因此,对于您的示例,我将这样做:
Invoke-NativeCommand cmd.exe /c "exit 1"
...,这会给我一个不错的PowerShell错误,看起来像:
cmd /c exit 1 exited with code 1.
At line:16 char:9
+ throw "$command $commandArgs exited with code $result."
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : OperationStopped: (cmd /c exit 1 exited with code 1.:String) [], RuntimeException
+ FullyQualifiedErrorId : cmd /c exit 1 exited with code 1.