"Darren Mar-Elia" <dmanonymous@xxxxxx> wrote in message
news:2B668D38-8B7F-434F-B23A-2F0967D18CDB@xxxxxx
> If I'm calling a cmdlet in a PSh script, what is the best way to trap for
> errors in the cmdlet? In other words, I call the cmdlet then do a bunch of
> things afterwards. I'd like to script to bail out if the cmdlet throws an
> exception. I'm sure this is easy, but just looking for the "right"
> approach.
> It sounds like to me that you don't need to trap errors. You just want to
enforce that if the cmdlet errors, the error is a terminating error instead
of a non-terminating error. To do this, use the ubiqitous
parameter -ErrorAction and set it to Stop e.g.:
Get-ChildItem someNameThatDoesntExist -ErrorAction Stop
This will cause script execution to jump to the previous trap handler in
scope and on up the call stack. If none exists the script will exit
automatically with that error.
Another option, if you want this behavior for all cmdlet calls within a
certain scope, is to set $ErrorActionPreference = 'Stop' before the cmdlet
invocations.
--
Keith