Fractal - Verbose in Powershell

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

I know that maybe I can find $ PSBoundParameters for the flag and execute the 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?

+6
source share
3 answers

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

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

Then, each command that you invoke with the -Verbose parameter will set it, depending on whether you used -Verbose when invoking the extended function.

If you have only a few commands, do the following:

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

What about:

 $vb = $PSBoundParameters.ContainsKey('Verbose') Invoke-CustomCommandB -Verbose:$vb 
+1
source

I started using the KeithHill $ PSDefaultParameterValues โ€‹โ€‹technique in some powershell modules. I came across some rather amazing behavior, which I am sure was the result of the sphere effect and $ PSDefaultParameterValues, which is a kind of global variable . I ended up writing a cmdlet called Get-CommonParameters (alias gcp ) and used the splat parameters to achieve the explicit and short cascading of -Verbose (and other common parameters). Here is an example of how it looks:

 function f1 { [CmdletBinding()] param() process { $cp = &(gcp) f2 @cp # ... some other code ... f2 @cp } } function f2 { [CmdletBinding()] param() process { Write-Verbose 'This gets output to the Verbose stream.' } } f1 -Verbose 

The source for the cmdlet Get-CommonParameters (alias gcp ) is located in this github repository .

0
source

Source: https://habr.com/ru/post/959364/


All Articles