This is quite a quick post, but a useful tip. If you are setting up some data in powershell which you then fire at the console via | Format-Table it can be useful to highlight specific rows.
Imagine you have a hashtable with the key as a string, and the value as a number. When you send to the console you will see the names and values set in a table.
1 |
@{"Bob"=1;"John"=3;} | Format-Table |
Now if you want to set John to be a certain colour then you can use the code below.
Note for static values this doesn’t add much value, we use it for a table that is getting printed dynamically e.g. based on a timer tick and dynamic version of the Name
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
@{"Bob"=1;"John"=3;} | Format-Table @{ Label = "Name" Expression = { if ("John" -eq $_.Name) { $color = "32" #green } else { $color = "0" #white } $e = [char]27 "$e[${color}m$($_.Name)${e}[0m" } }, Value |
This requires PowerShell 5.1 or later (check with $PSVersionTable.PSVersion
) and doesn’t seem to play fair with the PowerShell ISE, however from a normal PowerShell window or VSCode it works a charm.
Happy colouring 🙂