What is the right way to do error handling in PowerShell? What is the right way to do error handling in PowerShell? powershell powershell

What is the right way to do error handling in PowerShell?


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_ErrorsGet-Help about_Trap