Colour-coding get-content results

 ̄綄美尐妖づ 提交于 2019-12-18 12:29:29

问题


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

Now I want to get fancy!

I would like the font colour to change everytime a particular term is encountered. I can set the font colour easily enough, but how would you do it on-the-fly with the above statement?

Edit: Figured it out, but can't post an answer for 8 hours. Will upload it tomorrow.


回答1:


Try

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



回答2:


If you're looking for something that provides selective color coding, then try something like this.

First, set up a helper function to select an appropriate color:

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

Then execute a line that looks like this:

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


来源:https://stackoverflow.com/questions/6132140/colour-coding-get-content-results

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!