SolvedPowerShell Equivalent of bash set -e

I asked this question on twitter and it was suggested I post here.

Many people consider it good practice to start a bash script.

#! /bin/bash
set -eu

set -e tells the script to stop on first error
set -u tells the script to not allow undeclared variables

Although not everyone agrees

I think set -u and Set-StrictMode -Version 1.0 are equivalent.

I just wrote a set of Powershell scripts for managing an elasticsearch server. Then a few top-level scripts to tie them together.

It would have been really useful to be able to write something equivalent to...

set -e

$someValue = .\server-task-1.ps1
.\server-task-2.ps1 -using $someValue
.\task-that-requires-everything-else-suceeded.ps1

... but I couldn't find how to and ended up with something more like...

$someValue = .\server-task-1.ps1
if ($LastExitCode -ne 0) {
    exit $LastExitCode 
}

.\server-task-2.ps1  -using $someValue
if ($LastExitCode -ne 0) {
    exit $LastExitCode 
}

.\task-that-requires-everything-else-suceeded.ps1
if ($LastExitCode -ne 0) {
    exit $LastExitCode 
}

Apologies if this is already possible and I've missed it...

12 Answers

✔️Accepted Answer

$erroractionpreference = "stop" only works if Write-Error is called (such as an exception is raised). It doesn't do any checks against $lastexitcode. We can certainly look into adding another preference variable to throw an exception if $lastexitcode != 0.

Other Answers:

Anyone who's interested in this should review the RFC: https://github.com/PowerShell/PowerShell-RFC/pull/88/files

More Issues: