Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I debug a Windows PowerShell module in Visual Studio?

I'm trying to write a PowerShell module as a VB.NET project with Visual Studio 2015. I've been able to put a few commands together, compile the class library into a DLL, import the module into a PowerShell session and call the command I created. All good so far. But as I'm expanding this module I'm going to need to be able to debug it.

So I added another project to the solution, a console application. I set it as the startup project and referenced the PowerShell class in the first project. So far when I call the PowerShell function I wrote all the work is being done in the EndProcessing() subroutine. I can't call that from my console app because It's protected.

The question: How do I properly call my Get-TestCommand PowerShell function from a console app in such a way that Visual Studio knows I'm referencing code in a separate project and not the compiled DLL while triggering the breakpoints I put in the Powershell class library?

like image 614
DavidM Avatar asked Feb 09 '16 18:02

DavidM


1 Answers

It's possible to debug your cmdlet directly without needing a separate project.

Note that the .exe paths below are for the "native" application versions — 32-bit (Windows) Powershell on 32-bit Windows, 64-bit (Windows) Powershell on 64-bit Windows — and assume Windows is installed to C:.

Project configuration

For .NET (Core) projects in Visual Studio 2022

  1. Open the properties of your class library project.

  2. Under the Debug section, click the Open debug launch profiles UI link.

  3. In the Launch Profiles window, click Create a new profile (first button in the upper-left) and select Executable.

  4. Configure the new launch profile as follows:

    • Executable: C:\Program Files\PowerShell\7\pwsh.exe
    • Command line arguments: -NoLogo -Command "Import-Module '.\MyModule.dll'; Get-TestCommand;"

    Visual Studio 2022 class library project configuration for PowerShell debugging

  5. Close the Launch Profiles window.

  6. Click the downward-pointing arrow in the Start Debugging toolbar button and select the new launch profile.

For .NET Framework projects in Visual Studio 2022, or all .NET projects in Visual Studio 2019 and older

Open the properties of your class library project and configure the Debug tab as follows:

  • Start Action
    • Start external program: C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe or C:\Program Files\PowerShell\7\pwsh.exe
  • Start Options
    • Command line arguments: -NoLogo -Command "Import-Module '.\MyModule.dll'; Get-TestCommand;"

Visual Studio 2015 class library project configuration for Windows PowerShell debugging

Debugging in action

Debugging a Windows PowerShell cmdlet in Visual Studio 2015

like image 131
Lance U. Matthews Avatar answered Oct 19 '22 19:10

Lance U. Matthews