颜色编码 get-content 结果

11
我有一个 Powershell 脚本,用于监视日志文件,过滤出有趣的部分,并在它们被写入文件时呈现给我。非常有效。感兴趣的代码行如下: ```html

I've got a powershell script that monitors a log file, filters out the interesting bits and then presents those bits to me as and when they are written to the file. Works wonderfully. The line of interest is:

```
get-content "$logFile" -wait | where { select-string $searchTerm -inp $_ }

现在我想让它更加花哨!

我希望在遇到特定词语时能够改变字体颜色。我可以轻松地设置字体颜色,但如何在上述语句中实时更改呢?

编辑:已经解决,但要等8小时后才能发布答案。明天会上传。

2个回答

16

如果你正在寻找提供有选择性颜色编码的东西,那么可以尝试这个。

首先,设置一个帮助函数来选择适当的颜色:

function Get-LogColor {
    Param([Parameter(Position=0)]
    [String]$LogEntry)

    process {
        if ($LogEntry.Contains("DEBUG")) {Return "Green"}
        elseif ($LogEntry.Contains("WARN")) {Return "Yellow"}
        elseif ($LogEntry.Contains("ERROR")) {Return "Red"}
        else {Return "White"}
    }
}

然后执行一行看起来像这样的代码:

gc -wait $logFile | ForEach {Write-Host -ForegroundColor (Get-LogColor $_) $_}

1
你的回答更具体,符合我的要求。它可以工作,但是会随机打印以下错误:`Get-LogColor : 无法将参数“LogEntry”绑定到参数,因为它是一个空字符串。 在行:1 字符:156
  • ... (Get-LogColor $) $}
  • ~~
    • CategoryInfo : InvalidData: (:) [Get-LogColor], ParameterBindingValidationException
    • FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Get-LogColor`
- Dot_NET Pro
我没有看到你的源数据,但我只能假设你的日志文件中有空行,这在技术上会违反“Mandatory=$true”绑定规则。我已经在我的答案中删除了它;唯一的后果是你的空白日志文件行将被传递回控制台,但这也会发生在普通的“Get-Content (gc)”语句中。 - StevoInco
谢谢,现在它已经正常工作了。 这应该是被接受的答案。 - Dot_NET Pro

7

尝试

Get-Content $logFile -Wait |
  Select-String $searchTerm | 
  ForEach {write-host -ForegroundColor red $_.line}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接