0

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.

Quincy Bowers
  • 390
  • 2
  • 15

2 Answers2

2

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"}
Loïc MICHEL
  • 24,935
  • 9
  • 74
  • 103
0

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

Community
  • 1
  • 1
Frode F.
  • 52,376
  • 9
  • 98
  • 114
  • This would certainly work. But I would like to avoid adding extra flags to the Do-Stuff call. I am sure I recently read another solution that had the module inspecting the call stack to determine if a -Debug or -Verbose parameter was present. I will use this solution if it turns out I have to though. – Quincy Bowers Jan 09 '13 at 18:18
  • never heard about it, but at least now I get notifications on updates here. so if it's true, I might learn it soon too =) – Frode F. Jan 09 '13 at 19:11