How to colorise PowerShell output of Format-Table How to colorise PowerShell output of Format-Table powershell powershell

How to colorise PowerShell output of Format-Table


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


The accepted answer is incorrect, it is possible to colorize columns. The solution to getting conditional column colors is to use Write-PSObject.

Here are some wonderful examples with documented code and explanations.

From the above resource:

Write-PSObject $servers -MatchMethod Exact -Column "Manufacture" -Value "HP" -ValueForeColor Yellow -ValueBackColor Red -RowForeColor White -RowBackColor Blue;

enter image description here

I found this via a GitHub issue to add color formatting to Format-Table, which seems to be a feature PowerShell devs would like to add at some point.


You could colorize the row making use of a regular expression...

filter colorize-row{    Get-Process | Select-Object Id, Name, WS, Responding | foreach {        # Print 'red' row if WS greater than 100 MB        if([System.Math]::Round($_.WS/1MB,1) -match "^([0-9]|[0-9][0-9]|[1-9][0-9]?$|^100$)$"){            [console]::ForegroundColor="white"; $_;        } else {            [console]::ForegroundColor="red"; $_;        }    }}colorize-row

Output:

Enter image description here