Analog Powershell Bash `set -e`

How can I make Powershell behave like Bash with its flag set -e? set -emakes the Bash script "Exit immediately if a simple command exits with non-zero status."

I thought I could do this by installing $ErrorActionPreference="Stop", but this does not work. Suppose I have a scripta.ps1

$ErrorActionPreference="Stop"
& cmd /c "exit 1"
echo "cmd exited `$LastExitCode=$LastExitCode and `$?=$?"

If I run it

.\a. ; echo "a.ps1 exited `$LastExitCode=$LastExitCode `$?=$?"

To my surprise, he prints

cmd exited $LastExitCode=1 and $?=False
a.ps1 exited $LastExitCode=1 $?=True

What's happening?! I expected a.ps1 to come out after the first line, throwing an error and setting $? on false.

Is there official documentation explaining $ ErrorActionPreference? All I found was this coffee blog post.

+5
source share
1 answer

$ErrorActionPreference , , , , PowerShell.

a cmdlet : ? , Write-Host $ErrorActionPreference, Stop:

Write-Error blah

Get-ChildItem somepathwhichsurelydoesntexisthere

, , , , . , choice 1, ?

- , , . PowerShell , , , .

, :

function Invoke-NativeCommand {
  $command = $args[0]
  $arguments = $args[1..($args.Length)]
  & $command @arguments
  if (!$?) {
    Write-Error "Exit code $LastExitCode while running $command $arguments"
  }
}

, .

+9

All Articles