Reputation: 7124
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
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
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