2

Lets say I ran a command with ErrorAction Stop and it generated an error. I would like to know whether the error was originally terminating or not? I have the ErrorVariable or $Error object. Does ErrorVariable catches both kind of errors? I am looking for a property in .NET/PowerShell object which could tell me that this Error was terminating. Are exceptions generated for Non-Terminating errors too?

Plus, when I am writing a command on console (not ISE and not running a script, just single command on console), how can I suppress the Error using ErrorAction variable? Basically, there should not be any red output on the screen.

1 Answers1

-1

about_Try_Catch_Finally and about_Trap have some helpful information.

By default non terminating errors aren't caught by try catch but they will show up in $error. You can use -ErrorVariable to define another error variable (about_CommongParameter. So you could use a custom variable for a check for non terminating errors which might make your code easier readable.

By using SilentlyContinue the output is suppressed but the error is still recorded in the error variable.

Seth
  • 1,215
  • 15
  • 35
  • No property on error to that says 'Non Terminating' or 'Terminating'? –  Feb 23 '19 at 07:45
  • 1
    `Get-DoesNotExist; $error[0] | gm;`, no. As mentioned by definition you're not able to try and catch non terminating errors. As an example you could try catch and check error afterwards. If it does have an error a non terminating error happened. – Seth Feb 25 '19 at 06:34
  • lets say I have`Some-PowerShell Command`, and while executing it, if any non-terminating error happens, I want to perform action A, otherwise if any Terminating error happens, I want to perform action B. How should I use try catch/ErrorVariable to achieve it? –  Feb 26 '19 at 14:02
  • 1
    The best option would be to simply supply `-ErrorAction Stop` and just turn every non terminating error into a terminating one. That way you just need a try catch block. For the other ... well as described you use a regular try catch and check `$error` afterwards if it has any content. If it does something happened. – Seth Feb 27 '19 at 06:32
  • If I turn non-terminating error to terminating, how would I know if it was originally non-terminating? I think I might be able to use second option though. –  Feb 27 '19 at 07:25
  • If it's a non terminating error why do you care in the first place. Do proper validation for what you did afterwards. If what you find isn't what you expect raise an error (which will be hard either way). It's unclear what you're working on or where your requirement is coming from. In addition I pointed out what you can do otherwise. If you care so much about non terminating error you will likely handle it like a terminating one away. – Seth Feb 27 '19 at 08:51