Error and exception handling – Try/Catch
One of the more popular error and exception handling techniques is leveraging Try/Catch
methodology. The Try/Catch
block is used for handling terminating errors and has a very simple structure. You first use the Try { }
section of code and then use Catch { }
to catch any errors and perform actions based on the errors. In the instance that you catch an error, you can access the exception object by declaring $_
. The $_
refers to what is in the current pipeline. Since an error occurred during the Try
sequence, the data in the pipeline is the actual error information.
To use the Try/Catch
block, do the following action:
Try { 1+ "abcd" } Catch { Write-host "Error Processing the Command: $_" } Write-host "" ...
Get Mastering Windows PowerShell Scripting now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.