Try This PowerShell
In the previous article, we began looking into PowerShell's error system. As you learned, there is the exception object and the error message. You can control the error message with the ErrorActionPreference
variable. Although, we typically will control this on a per-command basis using the common ErrorAction variable. I also introduced you to non-terminating and terminating exceptions. This distinction is important because you can only handle or manage terminating exceptions. Today, I want to explore how you do just that.
In early versions of PowerShell, error handling was managed with the Trap statement. This has been long deprecated, so I'm not going to explain it. If you find code still using Trap statements, I would be very wary about the viability of the rest of the code, primarily because PowerShell has advanced so much since the days of trapping errors that other parts of the script probably need updating as well.
The proper way to handle exceptions in PowerShell is with Try/Catch. You should find some time to read the help topic about_try_catch_finally. In the meantime, let's look at how Try/Catch works.