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