Thursday, May 12, 2011

Debug Powershell C# Cmdlet

Now that I am able to create and load a C# Cmdlet as a module, the next thing I want is the ability to debug it.

Originally I wanted to be able to press the F5 key in Visual Studio and have it bring up a powershell window and attach to the process automatically.  That would have been elegant.  Alas it was not to be.  Turns out if you add a powershell.exe command to the Project Properties - Debug - Start External Program line you get this error.

External Program Path:
The external program cannot be found. Please enter a valid executable file.

You can actually ignore that message and attempt a debug anyways. I don't advice it because what happens is it sends the command to a non-interactive cmd.exe shell and sits and waits for a response, hanging the Visual Studio instance.

Next I tried this little gem:
cmd /c "start "newshell" powershell.exe  -nologo -noexit -noprofile"

This actually pops up an interactive shell and starts powershell.exe, but once again Visual Studio hangs until you exit that shell, never going into debug mode.

I tried the same thing using the post build events, with the same results.

So, to make things at least a little easier I created this powershell script to copy my files from my Visual Studio environment to the modules directory, then import the module into a new instance of Powershell.


Copy-Item C:\prj\PowershellCmdlets\PowershellCmdlets\bin\Debug\*.* "C:\Documents and Settings\<yourlogin>\My Documents\WindowsPowershell\modules\PowershellCmdlets" -Force
Import-Module PowershellCmdlets

So to debug:

  • Execute a build in Visual Studio
  • From a  Powershell window run the script file which will start up a fresh Powershell instance within the existing Powershell instance.
  • In Visual Studio debug menu attach to the Powershell process.
  • Set breakpoints in your code.
  • Go back to you Powershell window and run one of your new modules cmdlets.
  • Voila, your break point should be hit and you can begin debugging.


Once your done debugging you can go to the powershell window and type 'exit' and that will kill the thread and return Visual Studio to edit mode.

I will update this post if I find something more elegant.

No comments:

Post a Comment