I have a log file that contains ansi color codes around various text. I'm echoing it to the console using the powershell language command:
get-content logfile.log -wait
so I can see the latest log changes. However, all the ansi color codes show up as text characters like:
Esc[90mEsc[39m
How do you get them intepreted as color codes in the powershell window?
Not being very familiar with the powershell language yet, is there a powershell command or encoding option to handle this? I've read various powershell docs but haven't found anything in them re these ansi codes.
You can translate the ANSI escape codes for colors by splitting the text at ESC and translating the colors into Write-Host .... -Forground <color>
instructions.
function Open-Colored([String] $Filename)
{ Write-Colored(cat -Raw $Filename) }
function Write-Colored([String] $text)
{ # split text at ESC-char
$split = $text.Split([char] 27)
foreach ($line in $split)
{ if ($line[0] -ne '[')
{ Write-Host $line -NoNewline }
else
{ if (($line[1] -eq '0') -and ($line[2] -eq 'm')) { Write-Host $line.Substring(3) -NoNewline }
elseif (($line[1] -eq '3') -and ($line[3] -eq 'm'))
{ # normal color codes
if ($line[2] -eq '0') { Write-Host $line.Substring(4) -NoNewline -ForegroundColor Black }
elseif ($line[2] -eq '1') { Write-Host $line.Substring(4) -NoNewline -ForegroundColor DarkRed }
elseif ($line[2] -eq '2') { Write-Host $line.Substring(4) -NoNewline -ForegroundColor DarkGreen }
elseif ($line[2] -eq '3') { Write-Host $line.Substring(4) -NoNewline -ForegroundColor DarkYellow }
elseif ($line[2] -eq '4') { Write-Host $line.Substring(4) -NoNewline -ForegroundColor DarkBlue }
elseif ($line[2] -eq '5') { Write-Host $line.Substring(4) -NoNewline -ForegroundColor DarkMagenta }
elseif ($line[2] -eq '6') { Write-Host $line.Substring(4) -NoNewline -ForegroundColor DarkCyan }
elseif ($line[2] -eq '7') { Write-Host $line.Substring(4) -NoNewline -ForegroundColor Gray }
}
elseif (($line[1] -eq '3') -and ($line[3] -eq ';') -and ($line[5] -eq 'm'))
{ # bright color codes
if ($line[2] -eq '0') { Write-Host $line.Substring(6) -NoNewline -ForegroundColor DarkGray }
elseif ($line[2] -eq '1') { Write-Host $line.Substring(6) -NoNewline -ForegroundColor Red }
elseif ($line[2] -eq '2') { Write-Host $line.Substring(6) -NoNewline -ForegroundColor Gree }
elseif ($line[2] -eq '3') { Write-Host $line.Substring(6) -NoNewline -ForegroundColor Yellow }
elseif ($line[2] -eq '4') { Write-Host $line.Substring(6) -NoNewline -ForegroundColor Blue }
elseif ($line[2] -eq '5') { Write-Host $line.Substring(6) -NoNewline -ForegroundColor Magenta }
elseif ($line[2] -eq '6') { Write-Host $line.Substring(6) -NoNewline -ForegroundColor Cyan }
elseif ($line[2] -eq '7') { Write-Host $line.Substring(6) -NoNewline -ForegroundColor White }
}
}
}
}
Usage:
Open-Colored .\myColoredLogfile.log
来源:https://stackoverflow.com/questions/29583664/how-do-you-enable-powershell-to-interpret-ansi-color-codes-when-using-get-conten