views:

634

answers:

2

PowerShell is a weird mix of .bat and .NET. In .bat, you check errorlevel and stderr output from commands. In .NET, you catch exceptions.

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

I also assume that .NET functions I call in PowerShell will always throw exceptions and not get automatically caught by the shell and converted into errors. Is that correct?

Maybe what I really ought to ask is: what's a good article that goes over all of this? Seems like a lot of engineers out there like me who have experience in cmd's .bat and .NET both are wondering exactly how we ought to be doing things in this brave new world of Posh.

A: 

I consider Posh to be all .Net. Most of the concepts which work in .Net should work in Posh.

For Error handling, you can use Try..catch. It is also possible to "trap" errors and specify your own set of instructions to execute on an error condition.

I would highly recommend the in-built help:

Get-Help about_Errors
Get-Help about_Trap
Arun Mahapatra
So maybe it was removed in V2CTP3 but there is no about_errors or about_trap. And your response kind of sums up where my question came from.. Posh is .NET-y, I know about try-catch, etc., but it doesn't really help answer any of the questions I have.
Scott Bilas
+9  A: 

For individual cmdlets, there is a parameter called -erroraction. The possible values are SilentlyContinue, Stop, Continue, or Inquire. You can also specify a global variable called $errorpreference to any of these options.

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

Here is a quick example of using trap statements, the first is for a specif type of exception and the second is a generic catch all error trap

trap {"Other terminating error trapped" }
trap [System.Management.Automation.CommandNotFoundException] 
      {"Command error trapped"}
1/$null
Andy Schneider
Exactly what I needed, thanks so much!
Scott Bilas
The name of the global variable is $ErrorActionPreference, not $errorpreference: http://blogs.msdn.com/powershell/archive/2008/04/10/erroraction-update.aspx
Emperor XLII