Search code examples
powershellcolorsconsole

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


Solution

  • 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