gpt4 book ai didi

powershell - 在 PowerShell 控制台中对 native 命令行应用程序的输出日志进行着色

转载 作者:行者123 更新时间:2023-12-02 18:10:25 27 4
gpt4 key购买 nike

我正在使用 kubectl 从 pod 打印日志。 (我的 kubectl 和 powershell 冒险从今天开始)

我们的日志始终以以下内容开头:

[12:00:49 INF] ...
or
[12:00:49 WRN] ...
or
[12:00:49 ERR] ...

我的目标是根据日志级别查看这些线条的颜色。

我假设我需要向 $profile 添加某种脚本来分析 kubectl 的输出并逐行对其进行着色。

请注意,在 $profile 文件中,我已经有 kubectl 自动完成的脚本。

是否可以这样做,如果可以,请指导我如何做。

最佳答案

这可能会帮助您入门,它仅适用于 matches the pattern 的那些行。您可以为每个键值添加更多选项,例如 BackgroundColor 等。此技术使用 splatting确定线条的颜色。

$test = @"
[12:00:49 INF] hello
[12:00:49 WRN] world
[12:00:49 ERR] 123
[12:00:49 INF] 123
[12:00:49 WRN] world
[12:00:49 ERR] hello
"@ -split '\r?\n'

$map = @{
ERR = @{ ForegroundColor = 'Red' }
WRN = @{ ForegroundColor = 'Yellow' }
INF = @{ ForegroundColor = 'Green' }
}
[regex] $re = '^\[[\d:]+\s(' + ($map.Keys -join '|') + ')\]'

foreach($line in $test) {
# get the key we need to use for this line with regex
# and assign it to `$key`
if($key = $re.Match($line).Groups[1].Value) {
# if the line matched the pattern, get inner hashtable
$thisline = $map[$key]
# add this line to the inner hahstable
$thisline['Object'] = $line
# use splatting
Write-Host @thisline
# and go to next line
continue
}
# if the line didn't match the pattern, use default `Write-Host` values
Write-Host $line
}

关于powershell - 在 PowerShell 控制台中对 native 命令行应用程序的输出日志进行着色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72448000/

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