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}}
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}}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With