Quincy Bowers
Quincy Bowers

Reputation: 420

Module does not run Write-Debug when -Debug was passed in to calling script

I have a module that has the following function.

Test-Module.psm1

function Do-Stuff
{
    [CmdletBinding()]
    param($Stuff)
    Write-Debug 'Doing stuff!'
    Write-Host $Stuff
}

And I have a script that imports the module.

Test-Script.ps1

[CmdletBinding()]
param($Stuff)

Import-Module ./Test-Module.psm1

Write-Host 'About to do stuff.'
Do-Stuff -Stuff $Stuff
Write-Host 'Just did some stuff.'

But when I call the script the -Debug flag is not respected in the Do-Stuff function.

PS > .\Test-Script.ps1 -Stuff 'foobar'
About to do stuff.
foobar
Just did some stuff.

I recall seeing something on StackOverflow recently that discussed this very problem and suggested you could have the module examine the parameters up through the call stack to determine if it should implement the debugging or not. I can't find it now though and I'm not sure I understood how to implement at the time anyway.

How can I implement something like this, or something different that achieves the same goal.

Upvotes: 0

Views: 774

Answers (2)

Frode F.
Frode F.

Reputation: 54891

Simple solution: add a custom debug switch.

Test-Script.ps1

[CmdletBinding()]
param($Stuff, [switch]$UseDebug)

Import-Module ./Test-Module.ps1

Write-Host 'About to do stuff.'
Do-Stuff -Stuff $Stuff -Debug:$UseDebug
Write-Host 'Just did some stuff.'

Complicated solution: read the following SO question

Upvotes: 0

Loïc MICHEL
Loïc MICHEL

Reputation: 26160

one way may be to add this code on top of you module :

if ((get-pscallstack |select -last 2 |select -expand arguments -first 1) -match "verbose"){$verbosepreference="continue"}
if ((get-pscallstack |select -last 2 |select -expa arguments -first 1) -match "debug"){ $debugpreference="continue"}

Upvotes: 2

Related Questions