PowerShell Tips & Tricks: Getting more detailed error information from PowerShell

Allen White wrote this handy blogpost on how to handle error message and get more information out of an error record:

https://sqlblog.com/blogs/allen_white/archive/2009/06/08/handling-errors-in-powershell.aspx

There is an addtional method to get more information available. I found myself sending this little code snippet in email to many, and almost always I get the response that it saved that person with a ton of work, as new users to PowerShell are often left bewildered by the sparse error information; I had colleagues grabbing for the debugger to find the more detailed error messages...

An example; let's generate a simple error (recreate master will not work on most systems):

$db = new Microsoft.SqlServer.Management.Smo.Database
$db.Name = "master"
$db.Parent = get-item .
$db.Create()
Exception calling "Create" with "0" argument(s): "Create failed for Database 'master'. "
At line:1 char:11
+ $db.Create( <<<< )

Not very helpful is it?

Here is where this little gem comes in:

$error[0]|format-list -force

Now let's take a look at the details this emits:

Exception : System.Management.Automation.MethodInvocationException:
Exception calling "Create" with "0" argument(s): "Crea
te failed for Database 'master'. " ---> Microsoft.SqlSe
rver.Management.Smo.FailedOperationException: Create fa
iled for Database 'master'. ---> Microsoft.SqlServer.M
anagement.Common.ExecutionFailureException: An exceptio
n occurred while executing a Transact-SQL statement or
batch. ---> System.Data.SqlClient.SqlException: Databas
e 'master' already exists. Choose a different database
name.
at System.Data.SqlClient.SqlConnection.OnError(SqlEx
<cutting middle part out>
TargetObject :
CategoryInfo : NotSpecified: (:) [], MethodInvocationException
FullyQualifiedErrorId : DotNetMethodTargetInvocation
ErrorDetails :
InvocationInfo : System.Management.Automation.InvocationInfo

Well, now THAT's more like it!

As you can see the -force flag does a couple of nice things.

  1. It concatenates the error messages into a somewhat understandable result.
  2. It dumps stack information + all other error information avalable.

Generally it's a time saver as you have this command readily available for you at the command line.

Do you have any tips on error handling? I'd love to hear about it.

-Michiel