在 PowerShell 中编写详细包装器?

Write-Verbose Wrapper in PowerShell?

我有一个使用 Write-Verbose 调用的脚本。我想创建一个包装器 - 覆盖它,添加另一个调用,然后调用常规 Write-Verbose 命令。

类似于:

Function global:Write-Verbose ($msg) {
    MyLogger $msg
    Real-Write-Verbose $msg
}

我该怎么做?

可能 $ExecutionContext.InvokeCommand.GetCommand:

function Write-Verbose {
    [CmdletBinding()]
    param(
       [Parameter(Mandatory=$true, Position=0, ValueFromPipeline=$true)]
       [Alias('Msg')]
       [AllowEmptyString()]
       [System.String]
       ${Message})

    begin {
       try {
           $outBuffer = $null
           if ($PSBoundParameters.TryGetValue('OutBuffer', [ref]$outBuffer))
           {
               $PSBoundParameters['OutBuffer'] = 1
           }
           $wrappedCmd = $ExecutionContext.InvokeCommand.GetCommand('Write-Verbose', [System.Management.Automation.CommandTypes]::Cmdlet)
           $scriptCmd = {& $wrappedCmd @PSBoundParameters }
           $steppablePipeline = $scriptCmd.GetSteppablePipeline($myInvocation.CommandOrigin)
           $steppablePipeline.Begin($PSCmdlet)
       } catch {
           throw
       }
    }

    process {
       try {
           MyLogger $Message
           $steppablePipeline.Process($_)
       } catch {
           throw
       }
    }

    end {
       try {
           $steppablePipeline.End()
       } catch {
           throw
       }
    }
}

归功于 Joel Bennett@Poshcode

如果您只想在脚本范围内覆盖它(而不是在任何调用的脚本或函数中),您可以这样做:

function Private:Write-Verbose ($msg) {
MyLogger $msg
&{Write-Verbose $msg}
}