JamesThomasMoon
JamesThomasMoon

Reputation: 7124

colorize powershell stdout stderr

How can I colorize the standard out, stdout, and standard error, stderr, in a powershell terminal?

That is, run any command-line program in a typical powershell terminal. The program writes to stdout and stderr. The program should not have to be modified or aware of the color setting.
I want stdout to be white and stderr to be red.

Upvotes: 8

Views: 653

Answers (1)

radrow
radrow

Reputation: 7129

You can take advantage of the fact that the standard output gets normally streamed in most common cases, and also that redirection does not forget the initial handle. Therefore, a sample solution is to

  1. Redirect all handles to the standard one (as it only makes to the pipeline)
  2. Find out the original handle of the entry by checking its type
  3. Reprint the entry (coloring respectively to the handle)

In my tests this works quite well:

function Color {
    param (
        [Parameter(Mandatory)]
        [scriptblock]$Command,

        [System.ConsoleColor]$OutColor = [System.ConsoleColor]::White,
        [System.ConsoleColor]$ErrColor = [System.ConsoleColor]::Red,
        [System.ConsoleColor]$WrnColor = [System.ConsoleColor]::Yellow,
        [System.ConsoleColor]$VrbColor = [System.ConsoleColor]::Magenta,
        [System.ConsoleColor]$InfColor = [System.ConsoleColor]::Blue
    )

    & $command *>&1 | ForEach-Object {
        $PrintColor =
            if     ($_ -is [System.Management.Automation.ErrorRecord]) { $ErrColor }
            elseif ($_ -is [System.Management.Automation.WarningRecord]) { $WrnColor }
            elseif ($_ -is [System.Management.Automation.VerboseRecord]) { $VrbColor }
            elseif ($_ -is [System.Management.Automation.InformationRecord]) { $InfColor }
            else {$OutColor}
        Write-Host -ForegroundColor $PrintColor $_
    }
}

Test:

Color {
  Write-Output OUT;
  Write-Error ERR;
  Write-Warning WRN;
  Write-Verbose VRB;
  Write-Information INF;
  Write-Host -ForegroundColor Black HOST;
  1234
}

The output looks like (colorblind-friendly edited):

OUT  // white
ERR  // red
WRN  // yellow
INF  // blue
HOST // blue
1234 // white

Side note: Write-Host is forcefully treated as Information here, so this script overrides all coloring.

Upvotes: 3

Related Questions