powershelltry-catch

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 occurred.

E.g.:

try { something }
catch { "Error occurred" }
if (!error) {
"No Error occurred"
}

How can I test if no error occurred in the statement?


Solution

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

    $error.clear()
    try { something }
    catch { "Error occured" }
    if (!$error) { "No Error Occured" }