Debugging Powershell Modules in Visual Studio 2010


There are posts all over the web lamenting how difficult it is to debug a custom PowerShell Module from within Visual Studio 2010 but I found a simple way to do it that works every time.  It was tricky to get right at first, but this works like a champ.

Here are the steps:

  • Start Visual Studio
  • go the the Properties window for your custom Module Project
  • Select the ‘Start External Program’ radio button
  • enter “C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe” as the destination.  This will start PowerShell and attach the debugger to the instance

DebugPowerShellExternalProgram

  • Go down to the “Start Options” and enter the text below in the “Command Line Agruments” box, including all of the quotes (naturally, you will have to change the paths for your project):

-noexit -command “& { import-module -name ‘C:\Path\To\Solution\Project\bin\Debug\CustomModule.dll’}”

DebugPowerShellCommandLine

This last step loads your custom module into the PowerShell instance that is being debugged.  From there, simply set your breakpoints in Visual Studio and then call your new PowerShell command from within the new PowerShell window.  It should stop on your breakpoint every time.

Happy Debugging!

Advertisements

Posted on June 28, 2011, in Development. Bookmark the permalink. 3 Comments.

  1. This works well in Visual Studio 2010. But in Visual Studio 2012 the module gets imported as expected but no break points are hit. Do you know of any solution to this?

    Thanks

    • Roger, unfortunately I do not have a 2012 environment available that I can test this with but if I had to guess, it would be that something is mixed in the PowerShell environment itself, either 32/64-bit or PowerShell v3. I would love to hear if you find the culprit!

  2. You led me in the right direction! Installing PowerShell v3 solved my problem.

    I don’t really understand why it should be necessary. “Attach to Process” works fine with PowerShell v2 and VS2012, just not “Start Debugging” (F5). Anyway, they both work with PowerShell v3 and VS2012.

    Thanks!

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s