1

When creating a bash script, we can use set -e to say that the script should be aborted when anything fails. In PowerShell, we have something similar with $ErrorActionPreference = 'Stop'. For example, if I create a script like this:

$ErrorActionPreference = 'Stop'
SomeUnkownCommand
Write-Host "I don't want this line to be executed because previous line failed"

Then, the Write-Host command will not be executed.

But if I have a script like this that calls an external process:

$ErrorActionPreference = 'Stop'
$output = & sc.exe stop some_unknown_service
Write-Host "I don't want this line to be executed because previous line failed"

Then, the Write-Host command is executed and the script completes without any error.

If I don't want my script to continue after the external process fails, I must do something like this:

$ErrorActionPreference = 'Stop'
$output = & sc.exe stop some_unknown_service
if ($LASTEXITCODE -ne 0) 
{
    throw "External process failed with code $LASTEXITCODE"
}
Write-Host "I don't want this line to be executed because previous line failed"

This makes the code much less readable since I have to put these if all over my code.

Just like $ErrorActionPreference = 'Stop' in PowerShell and set -e in bash, is there a way to tell PowerShell to raise an error as soon as any external process fails?

mklement0
  • 382,024
  • 64
  • 607
  • 775
mabead
  • 2,171
  • 2
  • 27
  • 42
  • 1
    In short: as of PowerShell 7.0, this is not directly supported, unfortunately, but changing that has been proposed: see the [linked answer](https://stackoverflow.com/a/48877892/45375) for background info and a workaround via a small helper function. – mklement0 Feb 17 '20 at 20:51
  • However, here are the same results shown in your post without if - try/catch or ErrorActionPreference Write-Host 'Before command and error throw' -ForegroundColor Yellow SomeUnkownCommand throw $LASTEXITCODE -ne 0 Write-Warning -Message 'After error throw' Before command and error throw SomeUnkownCommand : The term 'SomeUnkownCommand' is ... Write-Host 'Before command and error throw' -ForegroundColor Yellow $output = & sc.exe stop some_unknown_service throw $LASTEXITCODE -ne 0 Write-Warning -Message 'After throw' Before command and error throw True At line:4 ... – postanote Feb 18 '20 at 00:27

0 Answers0