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.
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
.
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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With