Debugging functions in Module

I have a collection of PowerShell functions that I include in a PowerShell module. I use Plaster to generate .psd1 and .psm1 files from multiple .ps1 source script files that typically contain a single function.

I’m having difficulty coming up with a workflow that allows me to effectively debug modifications of a function. I am using VS Code (so much better than the PowerShell ISE!) and its debugger. The problem is that when I have modified code, PowerShell sometimes (but not always) keeps executing a previous version of the code. I haven’t found a reliable means of executing the modified code.

I’ve tried doing things like using Remove-Module to remove my module then dot-sourcing the modified file in the hope that when I invoke the function, the updated code will be executed. Sometime this works and sometimes it doesn’t. The most reliable procedure seems to be using Plaster to re-generate the module then deploying to the first folder in the ModulePath.

Is there a recommended way to debug code in a module?

Thanks

Mike

 

Where does the module live? It is located in your $env:PSModulePath? If so, you can do a Import-Module MyModule -Force and force PowerShell to use the updated module. If is not in your PSModulePath, you can import the module by using Import-Module C:\temp\MyModule.psm1 -Force it also depends on how your psd1 file is setup, it is hard to give an exact answer without knowing your setup.

pwshliquori

I hadn’t been using -Force on my Import-Module command. I tried that and at least the right version of the code runs. (I use a debugging helper that displays the name and modification date for the source of the function. It would have helped if PowerShell would display the path to the source file when the source isn’t a module with a manifest.

That’s a step in the right direction and it does let me open the module’s .psm1 file in VS Code and set a breakpoint which is hit. What it doesn’t seem to do is to provide a means to update the functions source except manually copying the changes and pasting them into the function’s .ps1 file.

While researching Import-Module -Force, I discovered that I could remove a function by using, for example, Remove-Item function:/Get-MyData to logically remove the function from its module. If I dot-source the function’s .ps1 file (e.g., . .\Public\Get-MyData.ps1) to define Get-MyData, I can set a breakpoint inside Get-MyData.ps1 and it actually works!

I’ll try using that approach and seeing how well it works. Unfortunately, I keep finding ways to debug that work perfectly for a while and stop working after “a while”.

Mike