Recursive -Verbose in Powershell

Viewed 1617

Is there an easy way to make the -Verbose switch "passthrough" to other function calls in Powershell?

I know I can probably search $PSBoundParameters for the flag and do an if statement:

[CmdletBinding()]
Function Invoke-CustomCommandA {
    Write-Verbose "Invoking Custom Command A..."

    if ($PSBoundParameters.ContainsKey("Verbose")) {
        Invoke-CustomCommandB -Verbose
    } else {
        Invoke-CustomCommandB
    }
}

Invoke-CustomCommandA -Verbose

It seems rather messy and redundant to do it this way however... Thoughts?

3 Answers

One way is to use $PSDefaultParameters at the top of your advanced function:

$PSDefaultParameterValues = @{"*:Verbose"=($VerbosePreference -eq 'Continue')}

Then every command you invoke with a -Verbose parameter will have it set depending on whether or not you used -Verbose when you invoked your advanced function.

If you have just a few commands the do this:

$verbose = [bool]$PSBoundParameters["Verbose"]
Invoke-CustomCommandB -Verbose:$verbose

How about:

$vb = $PSBoundParameters.ContainsKey('Verbose')
Invoke-CustomCommandB -Verbose:$vb
Related