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

Why does a PowerShell script not end when there is a non-zero exit code using the call operator?

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

使用以下示例,得到结果managed to get here with exit code 1

1
2
3
4
5
$ErrorActionPreference ="Stop"

& cmd.exe /c"exit 1"

Write-Host"managed to get here with exit code $LASTEXITCODE"

呼叫操作员的Microsoft文档没有讨论使用呼叫操作符时应发生的情况,它仅声明以下内容:

Runs a command, script, or script block. The call operator, also known as the"invocation operator," lets you run commands that are stored in variables and represented by strings. Because the call operator does not parse the command, it cannot interpret command parameters.

此外,如果这是预期的行为,是否还有其他方法可以让呼叫操作员导致错误而不是让错误继续?


返回代码不是PowerShell错误-与其他任何变量一样。

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

1
2
3
4
5
$ErrorActionPreference ="Stop"

& cmd.exe /c"exit 1"

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


在几乎所有的PowerShell脚本中,我都倾向于"快速失败",因此我几乎总是有一个看起来像这样的小函数:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
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."
    }
}

因此,对于您的示例,我将这样做:

1
Invoke-NativeCommand cmd.exe /c"exit 1"

...,这会给我一个不错的PowerShell错误,看起来像:

1
2
3
4
5
6
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.