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