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.
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.
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.