是否可以在Powershell中自定义详细消息前缀?

时间:2019-05-19 01:37:35

标签: powershell

当前的详细消息前缀只是VERBOSE:

我想将其修改为VERBOSE[N]:,其中N是当前线程ID。

有可能吗?

1 个答案:

答案 0 :(得分:0)

此行为(或更确切地说是格式字符串)被硬编码到默认的PowerShell主机中,没有钩子可以覆盖它。您必须实现自己的主机或修改调用代码才能使用适当的日志记录框架,但这两种都不是特别简单。

如果至少控制最外部的调用,则可以选择重定向详细的流输出,我们可以将其与c​​mdlet结合使用以“对”自定义内容进行排序:

function Verbosi-Tee {
    [CmdletBinding()]
    Param (
        [Parameter(ValueFromPipeline = $true)]
        $o
    )
    Process {
        if ($o -is [System.Management.Automation.VerboseRecord]) {
            Write-Verbose "[$([System.Threading.Thread]::CurrentThread.ManagedThreadId)] $($o.Message)"
        } else {
            $o
        }
    }
}

样品使用:

$VerbosePreference = "continue"

$x = (&{ 
    Write-Verbose "This is verbose." 
    Write-Output "This is just regular output." 
} >4&1 | Verbosi-Tee)  # redirect, then pipe

"We captured the output in `$x: $x"

输出(在我的系统上):

VERBOSE: [16] This is verbose.
We captured the output in $x: This is just regular output.

该cmdlet的名称是一个谎言,因为它实际上并没有实现完整的tee,但好的双关语是它自己的奖励。

相关问题