我有一个日志文件,其中包含各种文本周围的 ansi 颜色代码。我使用 powershell 语言命令将其回显到控制台:
get-content logfile.log -wait
这样我就可以看到最新的日志更改。但是,所有 ansi 颜色代码都显示为文本字符,例如:
Esc[90mEsc[39m
如何在 powershell 窗口中将它们解释为颜色代码?
还不太熟悉 powershell 语言,是否有 powershell 命令或编码选项来处理这个问题?我已经阅读了各种 powershell 文档,但没有在其中找到任何有关这些 ansi 代码的内容。
您可以通过在 ESC 处拆分文本并将颜色转换为颜色来转换颜色的 ANSI 转义码Write-Host .... -Forground <color>
指示。
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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)