What is the correct way to handle errors in PowerShell?

PowerShell is a strange combination of .bat and .NET. In .bat, you check for error output and stderr output from commands. In .NET, you encounter exceptions.

How do cmdlets return errors? Do they throw exceptions when they fail or do they set $? instead? Is this customizable?

I also assume that the .NET functions that I call in PowerShell will always throw exceptions and will not automatically get into the shell and convert to errors. It is right?

Maybe I should really ask: what is a good article that covers all this? It looks like I have a lot of engineers, I have experience in cmd.bat and .NET. They wonder how we should do something in this bold new world of Posh.

+7
exception powershell error-handling
source share
2 answers

For individual cmdlets, there is the -erroraction option. Possible values: SilentlyContinue, Stop, Continue or Inquire. You can also specify a global variable named $ errorpreference for any of these parameters.

In V1, you can use the trap keyword. There is a pretty good, concise article that describes the key differences between traps and the try / catch / finally syntax that was added in V2.

Here is a brief example of using trap statements, the first for a specific type of exception, and the second a common catch error trap

trap {"Other terminating error trapped" } trap [System.Management.Automation.CommandNotFoundException] {"Command error trapped"} 1/$null 
+9
source share

I believe that Posh is everything .Net. Most of the concepts that work in .NET should work in Posh.

You can use Try..catch to handle errors. It is also possible to "trap" errors and specify your own set of instructions to execute on error conditions.

I highly recommend the on-line help:

 Get-Help about_Errors Get-Help about_Trap 
0
source share

All Articles