How to: Debug a PowerShell Cmdlet

Posted Thursday, September 9, 2010 10:40 AM by CoreyRoth

In sticking with our theme of debugging things from yesterday, I thought I would write up a quick post on how to debug a cmdlet.  This may be obvious to you experienced developers out there, but someone new to writing cmdlets may not be familiar with the process.  Luckily, cmdlets are easier to debug than the Custom Index Connectors I talked about yesterday.  I hope to educate people as much as I can on how to build cmdlets, so that we can get more contributions to the SharePoint PowerShell Community Toolkit.  If you haven’t checked it out yet, please do. :-)

Once you have built your cmdlet, set a breakpoint in your code in Visual Studio.  Once you have done that, open a new PowerShell window (or a SharePoint Management Shell) and install your module or snapin.  The technique for debugging is the same whether you load your cmdlet with Add-PSSnapin or Import-Module.  In Visual Studio, go to Debug –> Attach to Process.  Scroll through the list and look for powershell.exe.  If you launched PowerShell using the SharePoint 2010 Management Shell icon you will notice the title in the list as shown below.

PowerShellCmdletDebugAttachToProcess

When you find the right process, select it and click the attach button.  Now, go to your PowerShell window and run your command.  If all goes according to plan, your breakpoint will be hit and you can step through the code of your cmdlet.

PowerShellCmdletDebug

That’s all there is to it.  Isn’t developing for PowerShell easy? The snippet of code you see above is actually from a new cmdlet I am releasing soon in the SharePoint PowerShell Community Toolkit that lets you test search queries from the command line.  I’ve already found it to be a handy cmdlet when I want to test a query using the API quickly.

Comments

# Twitter Trackbacks for How to: Debug a PowerShell Cmdlet - Corey Roth - DotNetMafia.com - Tip of the Day [dotnetmafia.com] on Topsy.com

Pingback from  Twitter Trackbacks for                 How to: Debug a PowerShell Cmdlet - Corey Roth - DotNetMafia.com - Tip of the Day         [dotnetmafia.com]        on Topsy.com

# re: How to: Debug a PowerShell Cmdlet

Monday, September 20, 2010 10:54 PM by Trevor Sullivan

Excellent article! I doubt this works for cmdlets written in PowerShell (aka. Advanced Functions), since you're not typically developing those in a Visual Studio environment (unless you're testing out PowerGUI VSX, of course)?

:-)

Cheers,

Trevor

# re: How to: Debug a PowerShell Cmdlet

Thursday, September 28, 2017 10:29 AM by Chuck Bradley

Works Great in VS2013!

Thanks.

Leave a Comment

(required) 
(required) 
(optional)
(required)