本文介绍了当使用调用运算符的非零退出代码时,为什么 PowerShell 脚本不会结束?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当使用调用运算符和 $ErrorActionPerference = "Stop" 时使用非零退出代码时,为什么 PowerShell 脚本不会结束?

Why does a PowerShell script not end when there is a non-zero exit code using when using the call operator and $ErrorActionPerference = "Stop"?

使用下面的例子,我得到的结果 managed to get here with exit code 1:

Using the following example, I get the result 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 呼叫运算符文档 没有讨论使用呼叫运算符时会发生什么,它仅说明以下内容:


The Microsoft documentation for the call operator does not discuss what should happen when using call operator, it only states the following:

运行命令、脚本或脚本块.调用运算符,也称为调用运算符",可让您运行存储在变量中并由字符串表示的命令.由于调用运算符不解析命令,因此无法解释命令参数.

此外,如果这是预期行为,是否还有其他方法可以让调用运算符导致错误而不是让它继续?


Additionally, if this is expected behaviour, is there any other way to have the call operator cause an error rather than let it continue?

推荐答案

返回码不是 PowerShell 错误 - 它与任何其他变量的显示方式相同.

The return code is not a PowerShell error - it's seen the same way as any other variable.

然后您需要对变量进行操作并使用 PowerShell throw 一个错误,以便您的脚本将其视为终止错误:

You need to then act on the variable and throw an error using PowerShell for you script to see it as a terminating error:

$ErrorActionPreference = "Stop"

& cmd.exe /c "exit 1"

if ($LASTEXITCODE -ne 0) { throw "Exit code is $LASTEXITCODE" }

这篇关于当使用调用运算符的非零退出代码时,为什么 PowerShell 脚本不会结束?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-24 08:12