gpt4 book ai didi

windows - 在使用 get-content 回显到屏幕时,如何启用 powershell 来解释 ansi 颜色代码?

转载 作者:可可西里 更新时间:2023-11-01 09:20:03 25 4
gpt4 key购买 nike

我有一个日志文件,其中包含各种文本周围的 ansi 颜色代码。我正在使用 powershell 语言命令将它回显到控制台:

get-content logfile.log -wait

所以我可以看到最新的日志变化。但是,所有 ansi 颜色代码都显示为文本字符,例如:

 Esc[90mEsc[39m

如何在 powershell 窗口中将它们解释为颜色代码?

还不太熟悉 powershell 语言,是否有 powershell 命令或编码选项来处理这个问题?我已经阅读了各种 powershell 文档,但没有在其中找到任何关于这些 ansi 代码的内容。

最佳答案

您可以通过在 ESC 处拆分文本并将颜色转换为 Write-Host .... -Forground <color> 来转换颜色的 ANSI 转义码。说明。

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 }
}
}
}
}

用法:

Open-Colored .\myColoredLogfile.log

关于windows - 在使用 get-content 回显到屏幕时,如何启用 powershell 来解释 ansi 颜色代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29583664/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com