我有一个使用Write-Verbose
调用的脚本。我想创建一个包装器 - 覆盖它,添加另一个调用,然后调用常规Write-Verbose
命令。
类似的东西:
Function global:Write-Verbose ($msg) {
MyLogger $msg
Real-Write-Verbose $msg
}
我该怎么做?
答案 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}
}