3

I've been using Unix for about 20 years, but only started using Powershell recently. I have a ps1 script that does a number of tasks.

I know I could check each of them, and throw if they error, but it would be good for the entire script just to exit on any errors - like set -e does in bash.

How can I make a Powershell script exit immediately upon any error?

Using pwsh 6.2.1.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494

1 Answers1

-1

Having just found the answer to my own question:

ErrorActionPreference does this.

$ErrorActionPreference='Stop'

at the top of the ps1 file.

mikemaccana
  • 110,530
  • 99
  • 389
  • 494
  • 1
    You can also use "-ErrorAction Stop" if you want it to stop on certain commands, rather than the whole script. – Skuld Jul 21 '19 at 17:16
  • 3
    Note that this applies to PowerShell commands only; `$ErrorActionPreference` has no effect on calls to _external programs_ reporting failure via `$LASTEXITCODE`. [This RFC](https://github.com/PowerShell/PowerShell-RFC/pull/88/files) aims to introduce an abort-on-failure mechanism for external programs too. – mklement0 Jul 21 '19 at 19:44
  • 1
    `$ErrorActionPreference` doesn't work (at least, for external commands). Please see [this](/a/57949447) and [this](/a/48877892) amazing answers. – Sasha Sep 13 '20 at 11:10