Welcome toVigges Developer Community-Open, Learning,Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

powershell - 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 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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to Vigges Developer Community for programmer and developer-Open, Learning and Share
...