开发者

Colour-coding get-content results

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 writte开发者_StackOverflown 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.


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


Try

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

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜