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

后端 未结 2 2124
忘了有多久
忘了有多久 2021-02-19 14:06

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

相关标签:
2条回答
  • 2021-02-19 14:24

    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.
    
    0 讨论(0)
  • 2021-02-19 14:35

    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" }
    
    0 讨论(0)
提交回复
热议问题