According to answers like this one and my own experience, Powershell can take care of propagating -Verbose (and -Debug) automatically, which is very convenient. However this stops working when the functions which I want to propagate verbosity to are in a module. Code used for testing this:
Create a directory called Mod
somewhere, suppose in c:, and add 2 files:
File c:ModFunctions.ps1
:
function Show-VerbosityB { [cmdletbinding()]Param()
Write-Output "Show-VerbosityB called"
Write-Verbose "Show-VerbosityB is Verbose"
}
File c:ModMod.psd1
:
@{
ModuleVersion = '1.0.0.0'
NestedModules = @('Functions.ps1')
FunctionsToExport = @('*-*')
}
Now crate the main script, say c:Foo.ps1
:
Import-Module c:Mod
function Show-VerbosityA { [cmdletbinding()]Param()
Write-Output "Show-VerbosityA called"
Write-Verbose "Show-VerbosityA is Verbose"
}
function Show-Verbosity { [cmdletbinding()]Param()
Write-Output "Show-Verbosity called"
Write-Verbose "Show-Verbosity is Verbose"
Write-Output "Testing propagation"
Show-VerbosityA
Show-VerbosityB
}
Show-Verbosity -Verbose
Results in
PS> . C:Foo.ps1
Show-Verbosity called
VERBOSE: Show-Verbosity is Verbose
Testing propagation
Show-VerbosityA called
VERBOSE: Show-VerbosityA is Verbose
Show-VerbosityB called
Why is the Write-Verbose in the module's function skipped, why does propagation not behave like it does for Show-VerbosityA? (If I just dot-source Functions.ps1 instead of importing the module, the line VERBOSE: Show-VerbosityB is Verbose
is printed). I could make propagation manual by e.g. calling Show-VerbosityB -Verbose:$PSBoundParameters['Verbose']
. Or are there other, preferrably shorter, ways? It is quite messy if functions behave differently depending on whether they are part of a module or dot-sourced.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…