Using Colors in PowerShell Console

by Mar 29, 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.

To colorize text, you can always use Write-Host and its -ForegroundColor and -BackgroundColor properties in any PowerShell version:

foreach($color1 in (0..15))
{
    foreach($color2 in (0..15))
    {
        Write-Host -ForegroundColor ([ConsoleColor]$color1) -BackgroundColor ([ConsoleColor]$color2) -Object "X" -NoNewline
    }

    Write-Host 
}
 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
XXXXXXXXXXXXXXXX 
 

By using VT escape sequences, you have a much wider range of colors that you can use. Pick any RGB color for foreground and background. Each channel can use 8 bits (0 – 255):

# Red/Green/Blue foreground
$r = 0
$g = 20
$b = 255

# Red/Green/Blue background
$rback = 255
$gback = 100
$bback = 0

$esc = [char]27

# compose escape sequence
"$esc[38;2;$r;$g;$b;48;2;$rback;$gback;${bback}mCOLORFUL TEXT$esc[0m"

The code below creates all possible colors and shows them as lines of 256 characters on top of each other, so you get a smooth glow effect:

$esc = [char]27
$setCursorTop = "$esc[0;0H"

foreach($rback in (0..255))
{
    foreach($gback in (0..255))
    {
        foreach($bback in (0..255))
        {

            foreach($r in (0..255))
            {
                foreach($g in (0..255))
                {
                    [System.Text.StringBuilder]$line = ""
                    foreach($b in (0..255))
                    {
                        $null = $line.Append("$esc[38;2;$r;$g;$b;48;2;$rback;$gback;${bback}mX$esc[0m")
                    }
                    
                    $text = $line.ToString()
                    Write-Host "$setCursorTop$Text"
                }

                Write-Host 
            }
        }
    }
}

Twitter This Tip! ReTweet this Tip!