Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell error handling: do something if NO error occured

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

like image 914
Walter81 Avatar asked May 08 '12 10:05

Walter81


People also ask

How do you catch specific errors in PowerShell?

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.

How do you catch non-terminating errors in PowerShell?

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.

What is $_ in PowerShell?

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.

What does SilentlyContinue do in PowerShell?

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.


1 Answers

Check the automatic-variable $error after you cleared it.

$error.clear()
try { something }
catch { "Error occured" }
if (!$error) { "No Error Occured" }
like image 198
CB. Avatar answered Sep 18 '22 12:09

CB.