Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to customize the verbose message prefix in Powershell?

Tags:

powershell

The current verbose message prefix is simply VERBOSE:

I would like to modify it to VERBOSE[N]:, where N is the current thread Id.

Is it possible?

like image 291
mark Avatar asked Sep 06 '25 03:09

mark


1 Answers

This behavior (or rather the format string) is hard-coded into the default PowerShell host and there are no hooks to override it. You'd have to implement your own host or modify the calling code to use a proper logging framework, neither of which are particularly simple.

If you at least control the outermost invocation, you have the option to redirect the verbose stream output, and we can use this in combination with a cmdlet to "sort of" customize things:

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
        }
    }
}

Sample use:

$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"

Output (on my system):

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

The name of the cmdlet is a lie because this doesn't in fact implement a full tee, but a good pun is its own reward.

like image 168
Jeroen Mostert Avatar answered Sep 09 '25 02:09

Jeroen Mostert