当使用调用运算符的非零退出代码时,为什么PowerShell脚本不会结束?

Pan*_*ood 8 powershell

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

使用以下示例,我得到结果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"
Run Code Online (Sandbox Code Playgroud)

调用运算符Microsoft文档没有讨论使用call运算符时应该发生什么,它只说明以下内容:

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


此外,如果这是预期的行为,是否有任何其他方法让调用操作符导致错误而不是让它继续?

Phi*_*hil 11

在我几乎所有的 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."
    }
}
Run Code Online (Sandbox Code Playgroud)

所以对于你的例子,我会这样做:

Invoke-NativeCommand cmd.exe /c "exit 1"
Run Code Online (Sandbox Code Playgroud)

...这会给我一个很好的 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.
Run Code Online (Sandbox Code Playgroud)


Jam*_* C. 9

返回代码不是PowerShell错误 - 它与任何其他变量的看法相同.

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

$ErrorActionPreference = "Stop"

& cmd.exe /c "exit 1"

if ($LASTEXITCODE -ne 0) { throw "Exit code is $LASTEXITCODE" }
Run Code Online (Sandbox Code Playgroud)

  • 我可以使用任何语法糖来使其变得更好吗?像 `& { cmd.exe /C "exit 1" } -FailIfNonZero` 之类的东西? (3认同)