【问题标题】:Colour-coding get-content results颜色编码获取内容结果
【发布时间】:2011-05-25 23:32:28
【问题描述】:

我有一个 powershell 脚本,它监控日志文件,过滤掉有趣的位,然后在将这些位写入文件时将它们呈现给我。效果很好。感兴趣的线是:

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

现在我想变得花哨!

我希望每次遇到特定术语时更改字体颜色。我可以很容易地设置字体颜色,但是您如何使用上述语句即时设置?

编辑:想通了,但 8 小时无法发布答案。明天上传。

【问题讨论】:

    标签: powershell powershell-2.0


    【解决方案1】:

    如果您正在寻找提供选择性颜色编码的东西,那么试试这样的东西。

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

    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 $_) $_}
    

    【讨论】:

    • 你的回答更具体,我想要什么。它有效,但它随机打印以下错误:Get-LogColor : Cannot bind argument to parameter 'LogEntry' because it is an empty string. At line:1 char:156 + ... (Get-LogColor $_) $_} + ~~ + CategoryInfo : InvalidData: (:) [Get-LogColor], ParameterBindingValidationException + FullyQualifiedErrorId : ParameterArgumentValidationErrorEmptyStringNotAllowed,Get-LogColor
    • 我没有看到你的源数据,但我只能假设你的日志文件中有空行,这在技术上会破坏'Mandatory=$true'绑定规则。我已经在我的回答中删除了这个;唯一的后果是您的空白日志文件行将直接传递回控制台,但这无论如何都会发生在普通的“Get-Content (gc)”语句中。
    • thnkx,现在可以正常工作了。这应该是公认的答案
    【解决方案2】:

    试试

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-19
      • 1970-01-01
      • 1970-01-01
      • 2019-11-06
      • 1970-01-01
      • 2013-07-20
      • 2012-03-16
      • 1970-01-01
      相关资源
      最近更新 更多