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?