PowerShell Traps vs Try/Catch

June 25, 2014 by · Leave a Comment
Filed under: PowerShell 

This post (http://blogs.msdn.com/b/powershell/archive/2009/06/17/traps-vs-try-catch.aspx) gives a great summary of Traps vs Try/Catch as shown below.

  • Trap:
    • Designed for admins
    • V1 and V2
    • Introduces a new scope
    • Is “global”, meaning it applies to all code in the same scope, before or after.
    • Does not support rethrow (an empty throw statement throws a special RuntimeException with the message “ScriptHalted”)
  • Try/Catch
    • Designed for developers
    • V2 only
    • Does not introduce a new scope
    • Guarded code is in the try statement block, not the entire scope containing the try statement
    • Supports finally
    • Supports rethrowing exceptions

As a developer I am always looking for new ways to improve my code. Pristine error handling is always a goal with any new code, whether it be PowerShell, C#, or something else. Here are some of the rules I try to follow when developing PowerShell scripts for SharePoint:


  • Use $ErrorActionPreference = “Stop” on all scripts so that exceptions are always caught in the “Catch” block. This line should go in the beginning of the “Try” block. Your “Finally” block should contain $ErrorActionPreference = “Continue”.
  • Use a robust logging capability so that you have a record of the changes made by your scripts. Consider using a separate log just for exceptions or anomalies. This can be hugely helpful when debugging your code.
  • Ensure that your “Catch” blocks are ordered from specific to generic. Look for specific errors first, less specific next, and so on all the way to your most generic.


  • Don’t use -ErrorAction SilentlyContinue. While it has its place, it is almost always preferable to catch an error rather than silently continuing past it.
  • Don’t overlook the need for proper exception management in all parts of your code. Doing so can result in difficult to recover changes to your SharePoint farm.

How to Use a SharePoint List to Log Application Errors

March 18, 2011 by · Leave a Comment
Filed under: Logging 

Occasionally, as a developer, you will not have access to the SharePoint log that is maintained within the file system. One way to get around this limitation is to make use of a SharePoint list as a location for logging application errors. This list can easily be created at the site collection root and then given very limited access for viewing. Here’s how it’s done…
Read more