0

I'm using System.Management.Automation.PowerShell to programmatically execute a PowerShell script from C# application. The PowerShell script loads a .Net dll which it uses to perform its activities.

var script = "Add-Type -Path 'MyLibrary.dll'; ....";

using (var powershell = PowerShell.Create()) {
    powershell.AddScript(script);

    powershell.Invoke();
}

Is it possible to somehow connect Visual Studio's debugger to the PowerShell object instance so that the debugger can seamlessly step from the C# application into the PowerShell script and from that script into MyLibrary.dll (assuming I have symbols for the dll)?

Edit: Based on the below, it appears that there may not be a way to seamlessly flow debugging in Visual Studio from C# to PowerShell. However, it is possible to use VS to debug the C# code that launches and that is launched by PowerShell.

Ben Gribaudo
  • 5,057
  • 1
  • 40
  • 75
  • 1
    do you mean that you want to use the Windows PowerShell Debugger API like this sample? https://code.msdn.microsoft.com/windowsapps/Windows-PowerShell-f5c03f2d. To debug the dll file, you could think about using the custom helper class: http://stackoverflow.com/questions/8062407/debug-c-sharp-dll-when-loaded-into-powershells-process-is-it-even-possible – Jack Zhai Nov 30 '16 at 08:02
  • @JackZhai-MSFT, thanks for those helpful links! Using `System.Diagnostics.Debugger.Launch();` (mentioned in the second link) allowed me to debug the .Net code called by PowerShell in Visual Studio. I was hoping that there was a way to do the same with the PowerShell script itself, but oh well. :-) – Ben Gribaudo Jan 12 '17 at 17:08
  • @JackZhai-MSFT, would you mind turning your comment (at least the part pertaining to `System.Diagnostics.Debugger.Launch();`) into an answer so that I can accept it. :-) – Ben Gribaudo Jan 12 '17 at 17:09
  • 1
    Post it as the answer:) – Jack Zhai Jan 13 '17 at 06:34

1 Answers1

1

You could debug the dll file by calling the following in your helper class:

System.Diagnostics.Debugger.Launch();
Ben Gribaudo
  • 5,057
  • 1
  • 40
  • 75
Jack Zhai
  • 6,230
  • 1
  • 12
  • 20