Why does a PowerShell script not end when there is a non-zero exit code 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?
if ($LASTEXITCODE -eq 1) { throw "Exit code is 1" }?if ($LASTEXITCODE -ne 0) { throw "Exit code is $LASTEXITCODE" }-ErrorActionto an external command, nor is it even standardized what error codes mean. If any non-zero exit code caused a PowerShell error, you'd be obliged to wrap every external command in atry .. catchjust to get work done. This would be massively annoying. PowerShell is still primarily a shell language, not a general programming language. (cmd.exedoesn't care about exit codes either, same story -- you're free to check them yourself, of course.)$ErrorActionPreferencetoStopdoes not work when a native command (i.e., running an executable) returns an error. You need to check$?and/or$LASTEXITCODE. See also windows - How to stop a PowerShell script on the first error?.