My Technical Notes

Saturday, 21 January 2017

PowerShell: Propogation of `-Verbose` option and `ShouldProcess` non-handling

The following is an answer I posted on StackOverflow that was about propagation of `-Verbose` and how it ain't respected by `ShouldProcess`.


I was looking to write exactly the same question, and I am writing this almost 7 years later. I am surprised that Microsoft's PowerShell team have not fixed this yet. I have reproduced the issue with PowerShell Version 6 Preview (latest version).

I have come up with a simple workaround, that is, inside the `Inner` function, we create an run a `scriptblock`, setting the `-Verbose` flag by checking `$VerbosePreference` which is correctly set to `Continue`, even though it is not respected by `ShouldProcess`:


Function Outer {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")]
    param([string]$Name)
    
    Process {
        Write-Host "Outer called";
        Inner $Name
    }
}

Function Inner {
    [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")]
    param([string]$Name)
    
    Process {
        if (-not ($PSBoundParameters.ContainsKey('Verbose'))) {
            $PSBoundParameters.Add('Verbose', [bool]$VerbosePreference -eq 'Continue');
        }
        
        & {
            [CmdletBinding(SupportsShouldProcess=$true, ConfirmImpact="Medium")]
   
            param([string]$Name)
            
            if ($PSCmdlet.ShouldProcess($Name, "Inner")) {
                Write-Host "Inner called";
            }
        } @PSBoundParameters;
    }
}

Export-ModuleMember *

No comments: