Search code examples
powershelldebugging.net-corepowershell-cmdletpowershell-core

What is an appropriate debugging workflow for Powershell Core modules?


My company has a .NET Powershell module, written in C# to allow advanced users to automate tasks in our product. Currently it targets Powershell 5 using .NET 4.6.1. We would like to allow customers using other operating systems to use it as well, and as it has no OS-specific code, porting it was straightforward.

However, I cannot find documentation on a debugging workflow that should be followed. In standard .NET Powershell, this was quite simple and required a one-time setup procedure:

  • Configure the debug executable to be the Powershell path
  • Set debug arguments to be a short script that loads the module and if appropriate, executes the function that is being tested.
  • Hit F5

However, this doesn't work for Powershell Core. Because the project depends on NuGet packages, the module registration fails with a dependency error. I was able to figure out another workflow but it's a bit more obtuse:

  • Navigate to the project directory
  • Execute dotnet publish -f netstandard2.0 -c debug
  • Execute Import-Module ./bin/Debug/netstandard2.0/publish/MyModule.dll
  • Execute $pid to find the PID
  • Attach to the PID via Attach to Process in Visual Studio

This works and I have debugged a few issues with this method, but it's not the most pleasant or efficient way to do it. I believe that there must be a better way that is just not well documented.


Solution

  • I originally came up with a script based approach that you can see in this post's history, but what I didn't know at the time was the CopyLocalLockFileAssemblies property which makes the debug directory look like how it used to look when working on .NET Framework. You just need to add this to your .csproj in a <PropertyGroup>:

    <CopyLocalLockFileAssemblies>true</CopyLocalLockFileAssemblies>
    

    Then, the debugging setup is just the same as any other .NET module loaded into a third party application:

    1. Right click on your Powershell module project and click properties
    2. Select Debug
    3. Set Launch to Executable
    4. Executable: C:\Program Files\PowerShell\6\pwsh.exe
    5. Arguments: -NoExit -Command "Import-Module C:\dev\my-module\bin\Debug\netstandard2.0\my-module.dll"
    6. Set your module as the startup project
    7. Hit F5 to begin debugging.