Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

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

colors - How to colorise PowerShell output of Format-Table

I try to colorise the column RAM in red if the value is greater than 100 MB:

Get-Process | Format-Table @{ Label = "PID"; Expression={$_.Id}},
            @{ Label = "Name"; Expression={$_.Name}},
            @{ Label = "RAM (MB)"; Expression={[System.Math]::Round($_.WS/1MB, 1)}},
            @{ Label = "Responding"; Expression={$_.Responding}}

Enter image description here

I try with Write-Host -nonewline, but the result is wrong.

Get-Process | Format-Table @{ Label = "PID"; Expression={$_.Id}},
            @{ Label = "Name"; Expression={$_.Name}},
            @{ Label = "RAM (MB)"; Expression={write-host -NoNewline $([System.Math]::Round($_.WS/1MB, 1)) -ForegroundColor red}},
            @{ Label = "Responding"; Expression={ write-host -NoNewline $_.Responding -fore red}}

Enter image description here

See Question&Answers more detail:os

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

1 Reply

0 votes
by (71.8m points)

Starting with PowerShell 5.1 or later you can use VT escape sequences to add colors to a single column, but only if your console supports VT escape sequences (e.g. Windows 10 Fall Creators Update, Linux or Mac, but not Windows 8 w/o a console emulator like ConEmu).

Here is an example that has the formatting specified in an expression, though the same could be used in a ps1xml file:

dir -Exclude *.xml $pshome | Format-Table Mode,@{
    Label = "Name"
    Expression =
    {
        switch ($_.Extension)
        {
            '.exe' { $color = "93"; break }
            '.ps1xml' { $color = '32'; break }
            '.dll' { $color = "35"; break }
           default { $color = "0" }
        }
        $e = [char]27
       "$e[${color}m$($_.Name)${e}[0m"
    }
 },Length

And the resulting output, note that the column width looks good, there are no extra spaces from the escape sequence characters.

Screenshot of dir output with colored names


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...