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

*爱你&永不变心* 提交于 2021-01-21 06:39:24

问题


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

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"

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

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.


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


回答1:


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

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" }



回答2:


In almost all my PowerShell scripts, I prefer to "fail fast," so I almost always have a small function that looks something like this:

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."
    }
}

So for your example I'd do this:

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

... and this would give me a nice PowerShell error that looks like:

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.


来源:https://stackoverflow.com/questions/47032005/why-does-a-powershell-script-not-end-when-there-is-a-non-zero-exit-code-using-th

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!