johni
johni

Reputation: 5568

Running and debugging Powershell modules in Visual Studio 2017

I'm developing a Powershell module in C#, in Visual Studio 2017. I am a bit surprised that the developing-experience is so bad in terms of running and debugging so I'm trying my luck here.

The way it works for me now is as follows:

  1. Implement the module
  2. Compile
  3. Start a new Powershell window
  4. Navigate to the bin/debug folder
  5. import the compiled DLL (import-module)
  6. Run the commands
  7. Close the Powershell window (as otherwise I cannot rebuild the project as the DLL file is locked)
  8. Fix bugs, and go back to step #2

In case I need to debug the code, I use VS2017 attach to process and debug the code (after step #5).

That is not ideal in terms of DX and I would like to have something better, as close as to this:

  1. Implement the module
  2. Compile
  3. Press F5 (start)
  4. Powershell window opens up with the module loaded
  5. Run the commands
  6. Breakpoints hit pause the program like we used to

How do I achieve that?

Upvotes: 2

Views: 1565

Answers (1)

Robert K
Robert K

Reputation: 106

I managed to get this work with help of above comment from @Glenn:

  • Start your debugging with external program

    C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe
    
  • and the parameter line

    -NoExit -command "Import-Module '<path to your module>'; " 
    

With this you can now start with F5 -> get a powershell window with your already loaded module and the Debugger is attached to this process.

But you have to be careful if your binary module is written to target .NET Standard. In this case it seems that the debugger (VS2017 15.8.9) is not able to detect which run-time modules to load. So no breakpoints hit at all in this scenario! My quick workaround here was to add another project with Console App targeting .NET framework 4.xy and use this other project as start project with above settings. Now my workflow exactly mirrors your second sequence (1-6). Unloading the dll is no issue because stop debugging does end the process.

Upvotes: 1

Related Questions