Geeks With Blogs
Reidar Husmo SharePoint from the trenches

SharePoint 2010 developers love Powershell. It really is a huge step forward. If you still haven't started to use it, do so.

But I got bit the other day, when I added a try-catch block to my code.

See if you can spot it:

Try

{

    $legen = Create-Object Reidar.Husmo.AwesomeClass

    $legen.Dary(42)

}

Catch

{

    "an error occurred"

}

As you no doubt immediately spotted, Powershell does not have a Create-Object. But the try-catch hides coding mistakes. There is no indication that things are not ok, not even "an error occurred" is returned.

If you examine the $Error object, you'll see that things are not ok, but that's not how we're used to look for errors.

Posted on Monday, February 13, 2012 3:49 AM SharePoint 2010 , Powershell | Back to top


Comments on this post: SharePoint Powershell try catch gotcha

# re: SharePoint Powershell try catch gotcha
Requesting Gravatar...
This is not isolated to Try/Catch. This is more about PowerShell not having a JIT. Things that would catch this include using a scripting environment that has intellisense and intelligent syntax error feedback. Using the intellisense will give you a hint that the cmdlet does not exist. A scripting tool with syntax checking would not catch this because it is technically not a syntax error.

When you do run this, you will receive a run-time error from the PowerShell runspace that should pinpoint the problem. Using a step debugger would catch the line at the point at which the error is detected, which is the way I would recommend testing new scripts.

Left by Richard Giles on Feb 19, 2012 9:00 AM

# re: SharePoint Powershell try catch gotcha
Requesting Gravatar...
@Richard Giles: Good points. I think the main problem stems from the fact that I treat PowerShell as a quick way to get things done, and that I do not treat it as carefully as normal code. No unit tests, no code review, often no source control, ...but lots of fun. I use PowerShell ISE, which does have Intellisense and syntax colouring. But it doesn't JIT to look for Create-Object, as you point out.
Left by Reidar Husmo on Feb 24, 2012 6:58 AM

Your comment:
 (will show your gravatar)


Copyright © Norgean | Powered by: GeeksWithBlogs.net