How to propagate -Verbose to module functions?
The reason this is happening is because the $VerbosePreference
is not propagated when the module is called.
I modified your script to explicitly print the value at the same points you are outputting via Write-Verbose
and Write-Output
.
This powershell.org post proposes adding this to the module, which worked like a charm for me:
if (-not $PSBoundParameters.ContainsKey('Verbose'))
{
$VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference')
}
One of the comments mentions bug report with link (it doesn't exist or I don't have permissions to view)
The issue is discussed in a TechNet post, with a link to a Get-CallerPreferance
function that addresses this issue.
Module:
function Show-VerbosityB { [cmdletbinding()]Param()
<# uncomment to get verbose preference from caller, when verbose switch not explicitly used.
if (-not $PSBoundParameters.ContainsKey('Verbose'))
{
$VerbosePreference = $PSCmdlet.GetVariableValue('VerbosePreference')
}
#>
Write-Output "`nShow-VerbosityB called"
Write-output "Global pref: $($global:VerbosePreference)"
Write-output "Script pref: $($script:VerbosePreference)"
Write-output "Effect pref: $VerbosePreference"
Write-Verbose "Show-VerbosityB is Verbose"
}
Caller:
Import-Module C:\Mod
Write-output "On startup: $VerbosePreference"
function Show-VerbosityA { [cmdletbinding()]Param()
Write-Output "`nShow-VerbosityA called"
Write-output "Global pref: $($global:VerbosePreference)"
Write-output "Script pref: $($script:VerbosePreference)"
Write-output "Effect pref: $VerbosePreference"
Write-Verbose "Show-VerbosityA is Verbose"
}
function Show-Verbosity { [cmdletbinding()]Param()
Write-Output "`nShow-Verbosity called"
Write-output "Global pref: $($global:VerbosePreference)"
Write-output "Script pref: $($script:VerbosePreference)"
Write-output "Effect pref: $VerbosePreference"
Write-Verbose "Show-Verbosity is Verbose"
Write-Output "`nTesting propagation"
Show-VerbosityA
Show-VerbosityB
}
Show-Verbosity -Verbose