Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 999
Alban Avatar asked Dec 20 '13 13:12

Alban


1 Answers

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

like image 72
Jason Shirk Avatar answered Oct 15 '22 08:10

Jason Shirk