27

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

4
  • 1
    Have a read of this article, it may help powershellmagazine.com/2013/06/20/… Commented Dec 20, 2013 at 14:33
  • I supplied an answer but it doesnt color columns, just rows. Commented Dec 20, 2013 at 19:32
  • 1
    You can colorize columns differently, the accepted answer is no longer true, you need to use Write-PSObject. See my answer below. Commented Sep 11, 2017 at 15:08
  • Unfortunately, so far none of the answeres below accounts for the fact that columns might get truncated causing the color not being reset in Windows PowerShell 5.1, see: How to (correctly) colorize PowerShell 5.1 default output. Commented Aug 9, 2024 at 6:06

7 Answers 7

50

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:

Get-ChildItem -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

Sign up to request clarification or add additional context in comments.

4 Comments

There was an announcement about (maybe) 16bit support. Is that related to this feature, or something different?
Yes, 256 and 24bit color is supported by some terminals, the link in my answer describes that as well.
this is pure gold. thx! what i made from it gist.github.com/SeidChr/6dcae356760197d3d9147a3414829945
If anyone's tempted to declare the magic strings & numbers and improve readability, see stackoverflow.com/questions/16347214/….
20

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.

2 Comments

It seems the links in your answer no longer point to the right place, only the GitHub issue is still correct.
I like this solution, but the original question was about how to colorize the output of Format-Table.
12

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

2 Comments

Is there a way to format like when using Format-Table? I tried the @{n="<heading>"; e={$_.<value>}; a="left"} syntax, but it doesn't work.
This answer is no longer true, you can colorize columns, see my answer.
6

Here is a different version of Jason Shirk's answer after a few years now using $PSStyle in PowerShell 7.4

enter image description here

# Create a dummy data table with three columns: Name, Age, and Occupation
$data = @(
    [PSCustomObject]@{Name = 'Alice'; Age = 25; Occupation = 'Teacher' }
    [PSCustomObject]@{Name = 'Bob'; Age = 30; Occupation = 'Engineer' }
    [PSCustomObject]@{Name = 'Charlie'; Age = 35; Occupation = 'Doctor' }
    [PSCustomObject]@{Name = 'David'; Age = 40; Occupation = 'Lawyer' }
    [PSCustomObject]@{Name = 'Eve'; Age = 45; Occupation = 'Artist' }
)

$PSStyle.Formatting.TableHeader = "$($PSStyle.Foreground.FromRGB(218,112,214))"

$data | Format-Table @{
    Label      = 'Name'
    Expression =
    { switch ($_.Name) {
            { $_ } { $color = "$($PSStyle.Foreground.FromRGB(255,255,49))$($PSStyle.Blink)" } # Use PSStyle to set the color
        }
        "$color$($_.Name)$($PSStyle.Reset)" # Use PSStyle to reset the color
    }
}, @{
    Label      = 'Age'
    Expression =
    { switch ($_.age) {
            { $_ -gt 30 } { $color = "$($PSStyle.Foreground.FromRGB(255,20,147))$($PSStyle.Blink)" } # Use PSStyle to set the color
        }
        "$color$($_.age)$($PSStyle.Reset)" # Use PSStyle to reset the color
    }
}, @{
    Label      = 'Occupation'
    Expression =
    { switch ($_.Occupation) {
            { $_ } { $color = "$($PSStyle.Foreground.FromRGB(152,255,152))$($PSStyle.Blink)" } # Use PSStyle to set the color
        }
        "$color$($_.Occupation)$($PSStyle.Reset)" # Use PSStyle to reset the color
    }
}

Comments

5

The quick answer is that you can't. It's possible to use Write-Host with colors, but there's no "output" to send to format-table.

The "output" from Write-Host is a side-effect that sends data directly to the console rather than returning it to the caller like a standard function.

In conjunction with the comment by @David Martin, here's a link with an interesting pattern-matching format-color function.

Comments

2

Yes, you can use ANSI Escape colors and have the colors conditional:

Get-Process | Format-Table @{ Label = "PID"; Expression={$_.Id}},
        @{ Label = "Name"; Expression={$_.Name}},
        @{ Label = "RAM (MB)"; Expression={if($_.WS/1MB -gt 100){"$([char]27)[0;31m$([System.Math]::Round($_.WS/1MB, 1))$([char]27)[0m"}else{"$([char]27)[0;32m$([System.Math]::Round($_.WS/1MB, 1))$([char]27)[0m"}}},
        @{ Label = "Responding"; Expression={if($_.Responding -eq $true){"$([char]27)[0;32m$($_.Responding)$([char]27)[0m"}else{"$([char]27)[0;31m$($_.Responding)$([char]27)[0m"}}}

Comments

0

This example shows event records with alternating background colours of the rows (thanks to this post). Based on the TimeCreated field, the text colour will be blue (one month or less), yellow (one week or less) or red (today). See the 'ANSI Escape code' subject on Wikipedia for colour escape codes.

# constants
$e=[char]27                                             # escape character
[string]$_Reset     = $($e+"[0m")
[string]$_bSapphire1= $($e+"[48;2;1;36;86m")        # ESC[48;2;r;g;bm Select RGB background colour
[string]$_bSapphire2= $($e+"[48;2;3;55;155m")
[string]$_fBRed     = $($e+"[91m")
[string]$_fBYellow  = $($e+"[93m")
[string]$_fBCyan    = $($e+"[96m")
$Today              = [datetime]::today
$OneWeek            = $Today.AddDays(-7)
$OneMonth           = $Today.AddDays(-30)
# variable
[ref]$bToggle       = $True                         # makes the background colour of the row alternate
# script block
$ExtractScript={
    param([array]$Events,[enum]$Level)
    $Events|
    Where-Object { $Level -eq $_.Level }|
    Sort-Object -Property @{ Expression="ProviderName"; Ascending=$True },
                          @{ Expression="TimeCreated" ; Ascending=$True }|
    Format-Table @{
            Label="TimeCreated"
            Expression= {
                # rows have an alternating background colour
                if($bToggle.Value) { $bcolour=[string]::copy($_bSapphire1) } else { $bcolour=[string]::copy($_bSapphire2) }
                $bToggle.Value = $(-not $bToggle.Value)
                
                # TimeCreated has effect on the foreground colour of the row 
                $fcolour = [string]::copy($_Reset)
                if( $OneMonth -lt $_.TimeCreated ) { $fcolour = [string]::copy($_fBCyan) }
                if( $OneWeek  -lt $_.TimeCreated ) { $fcolour = [string]::copy($_fBYellow) }
                if( $Today    -lt $_.TimeCreated ) { $fcolour = [string]::copy($_fBRed) }
                $($fcolour+$bcolour+$("{0:d} {0:HH}:{0:mm}:{0:ss}" -f $($_.TimeCreated)))
            }
            Alignment='Right'
        },
        ProviderName,
        ID,
        @{
            Name='Level'
            Expression={$_.LevelDisplayName}
            Alignment='Right'
        },
        @{
            Name='Message'
            Expression={
                # Colours are reset
                $($_.Message+$_Reset)
            }
        }       
}
# code
$EventArray=Get-WinEvent -LogName System -MaxEvents 10000
& $ExtractScript -Events $EventArray -Level $([System.Diagnostics.Eventing.Reader.StandardEventLevel]::Error)
$($_Reset+"Legend:")|Out-Default
$($_fBCyan+"After "+$("{0:d} {0:HH}:{0:mm}:{0:ss}" -f $OneMonth))|Out-Default
$($_fBYellow+"After "+$("{0:d} {0:HH}:{0:mm}:{0:ss}" -f $OneWeek))|Out-Default
$($_fBRed+"Today")|Out-Default   
$_Reset|Out-Default

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.