Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there an equivalent of " ... || die" in powershell?

Tags:

powershell

Kind of like <statement> || die in perl, something concise that I can put with every critical statement to avoid bothering powershell with the rest of the script if something goes wrong.

like image 433
Lyt_Seeker Avatar asked Apr 02 '15 11:04

Lyt_Seeker


2 Answers

Most commands support the -ErrorAction common parameter. Specifying -ErrorAction Stop will generally halt the script on an error. See Get-Help about_CommonParameters.

By default, -ErrorAction is Continue. You can change the default option by changing the value of $ErrorActionPreference. See Get-Help about_Preference_Variables.

If verbosity is really an issue, -ErrorAction is aliased to -ea.

like image 200
Bacon Bits Avatar answered Sep 29 '22 06:09

Bacon Bits


Another way to implement a ...|| die-like construct in PowerShell without the need to add huge try-catch constructs, would be to use the automatic variable $?.
From Get-Help about_Automatic_variables:

$?  
   Contains the execution status of the last operation. It contains
   TRUE if the last operation succeeded and FALSE if it failed.

Simply add the following right after each critical statement:

if(-not $?){
    # Call Write-EventLog or write $Error[0] to an xml or txt file if you like
    Exit(1)
}
like image 20
Mathias R. Jessen Avatar answered Sep 29 '22 07:09

Mathias R. Jessen