PowerShell中的Write-Verbose Wrapper?

时间:2015-02-26 10:13:58

标签: powershell override wrapper io-redirection

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

类似的东西:

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

我该怎么做?

2 个答案:

答案 0 :(得分:1)

可能$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

答案 1 :(得分:1)

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

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