Reputation: 7228
I have a powershell script and I have set the $DebugPreference
to "Continue"
. However when I call Write-Debug
from a module that is called from my script, the $DebugPreference
changed to "SilentlyContinue"
. Why is that? How can I keep $DebugPreference
the same as the calling script? Example below
CallingScript.ps1
$DebugPreference = "Continue"
Write-Host "Debug preference: $DebugPreference"
Write-Debug "Checking that debugging works"
Import-Module Logging;
Write-Log "Debug" "Checking that debugging still works!"
Logging.psm1
Function Write-Log
{
param (
[ValidateSet("Error","Warning","Debug","Info")][String]$type,
[String]$logMessage
)
Write-Host "Debug preference: $DebugPreference"
switch($type)
{
"Error" {Write-Error $logMessage;}
"Warning" {Write-Warning $logMessage;}
"Debug" {Write-Debug $logMessage;}
"Info" {Write-Output $logMessage;}
}
}
If I run the script, this is the output:
PS > .\CallingScript.ps1
Debug preference: Continue
DEBUG: Checking that debugging works
Debug preference: SilentlyContinue
PS >
Upvotes: 5
Views: 7032
Reputation: 43605
As JPBlanc's link in his comment explains: It is a variable scope issue. The module's scope chain goes directly to the global scope and not through any script scopes. Even if it is imported from a script.
Your code will work if you set $DebugPreference from your script in the global scope, but of course this has influence on more than just your script.
$global:DebugPreference = "Continue"
Another solution in this specific $DebugPreference case is to use the -Debug parameter to pass it along. The downside is that you will have to do this with every command you call.
Write-Log "Debug" "Checking that debugging still works!" -debug:$DebugPreference
A third solution would be to set $DebugPreference at the module level.
$m = Import-Module Logging -PassThru
& $m {$script:DebugPreference = 'Continue'}
Upvotes: 11