I've been searching around for this but can't seem to find it. I'm having a script with a try {} catch {} statement. I'd like to add an action if NO error occured.
Eg
try { something }
catch { "Error occured" }
if (!error) {
"No Error Occured"
}
How can I test if no error occured in the statement?
Thanks in advance
Walter
Use the try block to define a section of a script in which you want PowerShell to monitor for errors. When an error occurs within the try block, the error is first saved to the $Error automatic variable. PowerShell then searches for a catch block to handle the error.
You can save off the non-terminating errors to a shell variable using the “-ErrorVariable” ubiquitous parameter (“-ev” is the parameter alias). This is not affected by “-ErrorAction”. You can also append failures to an existing ErrorVariable by prepending “+” to the variable name.
The “$_” is said to be the pipeline variable in PowerShell. The “$_” variable is an alias to PowerShell's automatic variable named “$PSItem“. It has multiple use cases such as filtering an item or referring to any specific object.
SilentlyContinue — Don't display an error message continue to execute subsequent commands. Continue — Display any error message and attempt to continue execution of subsequence commands. Inquire — Prompts the user whether to continue or terminate the action. Stop — Terminate the action with error.
Check the automatic-variable $error
after you cleared it.
$error.clear()
try { something }
catch { "Error occured" }
if (!$error) { "No Error Occured" }
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