Error Handling with Powershell

Error Handling

VBScript's On Error Resume Next statement, and the corresponding On Error Goto 0 statement, are used to implement error handling. Essentially, you execute On Error Resume Next before any operation that may result in an error, and then check the special Err object to see if an error did indeed occur. VBScript's error handling is actually quite primitive, while PowerShell's is much more advanced.

In brief, you declare a trap, which is what PowerShell executes when an error (or exception) occurs (or is thrown). You do whatever you need to do within the trap, and then tell PowerShell to either continue, which resumes execution on the line following whatever line caused the exception, or break, which halts execution. For example:

Trap {
  # handle error here
  Continue
}