Colorizing Cmdlet Output

by Mar 30, 2018

Starting in PowerShell 5.1, the PowerShell console supports VT escape sequences that can be used to position and format console text. Note that this works in the console only, not the PowerShell ISE. Note also that you either need Windows 10 or an emulator like ConEmu.

When you submit a hash table to Select-Object, the hash table can produce “calculated” columns. It provides two pieces of information: Name (the column name) and Expression (a script block that produces the column content).

This can be easily utilized to colorize cmdlet output. Simply create an expression that adds VT escape sequences for colors. In the example below, some file types are colorized:

$ColoredName = @{
    Name = "Name"
    Expression =
        switch ($_.Extension)
            '.exe'    { $color = "255;0;0" break }
            '.log' { $color = '' break }
            '.ini'    { $color = "0;0;255" break }
            default    { $color = "255;255;255" }
        $esc = [char]27

Get-ChildItem $env:windir | 
    Select-Object -Property Mode, LastWriteTime, Length, $ColoredName

Twitter This Tip! ReTweet this Tip!