Search code examples
powershellcolorspowershell-coreverbose

Changing Verbose colors in PowerShell 7.2


I expected the following code to print verbose text with my default foreground color:

$Host.PrivateData.VerboseForegroundColor = [console]::ForegroundColor
Write-Verbose 'Test' -Verbose

However, it prints yellow text as usual. Changing the Error foreground color does work though:

$Host.PrivateData.ErrorForegroundColor = [console]::ForegroundColor
Write-Error 'test'

The only way I've found to circumvent this is by doing this:

Write-Verbose 'Test' -Verbose *>&1 | Write-Host

But this isn't really changing the verbose colors, it's just forcing it to print directly to the console host as default text using Write-Host. I do know that Write-Host does let you alter the message color to anything you want, but this is hardly an ideal solution.


Solution

  • In Powershell 7.2+, $Host.PrivateData not the right way to set styles. It's there for backwards compatibility. For details, see a brand new about_* page: about_ANSI_Terminals

    You want

    enter image description here

    $PSStyle.Formatting.Verbose = $PSStyle.Foreground.FromRgb(0x34f2aa)
    

    Check out the docs, it adds a bunch of options: bold, blink, hidden, reverse, italic, underline, fileinfo.... about_ANSI_Terminals

    Test it out

    function testVerbose { 
       [CmdletBinding()]
       param( [Parameter() ]$x )
       "$x"
       $X.GetType().FullName | write-verbose
       
    }
    
    testVerbose 34.5 -Verbose                                             ; 
    
    $PSStyle.Formatting.Verbose = $PSStyle.Foreground.FromRgb(0x34f2aa)
    
    testVerbose 34.5 -Verbose
    

    Viewing ansi escapes

    One way to view the ANSI control chars is to replace "``e".

    # I saved the value before changing it
    $originalVerbose -replace "`e", ''
    
    $PSStyle.Formatting.Verbose -replace "`e", ''
    

    enter image description here

    Notice: It switched to the 24bit-color ANSI escape sequence

    Printing all control chars

    Format-ControlChar converts all control chars to their Symbol version, not just e, making values safe to pipe.

    It's easy, just add 0x2400 to the codepoint. compart.com/block/U+2400

    🐒> "$($PSStyle.Background.BrightCyan)Power$($PSStyle.Underline)$($PSStyle.Bold)Shell$($PSStyle.Reset)"
        | Format-ControlChar
    
    ␛[106mPower␛[4m␛[1mShell␛[0m