Tuesday, September 23, 2014

Debugging Powershell Cmdlets (C#)

When building Cmdlets in C# for Powershell one of the things you typically want to do is hit F5 to debug your Cmdlet code.
Fortunately this is quite easy to set up. Below I will be showing how to do it in Visual Studio 2012 - but I expect the process to be nearly identical in other Visual Studio versions.

You only need to do two things:
  1. Create a test script that loads and executes your cmdlet.
  2. Set project to use Powershell as startup application, and the test script as startup argument.

How I did it:

I created a simple Powershell script file (test.ps1) that I placed in my project, and set Build Action to None and Copy to Output Directory to Always.
The script points to the generated dll and loads it as a module. Then it calls a cmdlet in my project.


Next, I opened project properties for the project, and I went to the Debug setting.
Under Startup Action choose 'Start external program', and set it to 'c:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe'.
Under Start Options set Command line arguments to '-noexit .\test.ps1'.


Now, when I press F5 the solution builds, Powershell is launched, and myscript is run. I can set breakpoints in the Cmdlet, and it will get hit, allowing me to step through the code one piece at a time, and doing all the usual debugging stuff.

Just for reference, here is the cmdlet that I used in the example:


No comments:

Post a Comment