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
- Redirect all handles to the standard one (as it only makes to the pipeline)
- Find out the original handle of the entry by checking its type
- 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.