Table of random numbers
Let's setup a table of numbers:
$items = foreach ($i in 0..10)
{
[PSCustomObject]@{
a = Get-Random -Minimum -10.0 -Maximum 10.0
b = Get-Random -Minimum -10.0 -Maximum 10.0
}
}
If we display them:
$items | Format-Table
it'll look something like this:
PS C:\Users\dharm> $items | Format-Table
a b
- -
-7.26 6.45
3.22 -3.66
-8.41 -7.65
8.93 1.02
-5.92 -9.02
-8.06 -4.86
4.86 -1.57
-6.85 -7.35
3.97 -4.80
3.39 7.82
5.01 9.75
Conditional formatting
I'd like to display the positive numbers in green and the negative numbers in red.
Here's a color-number
function that uses PSStyle
:
function color-number ($val)
{
if ($val -gt 0) {
$PSStyle.Foreground.Green + ('{0,5:N2}' -f $val) + $PSStyle.Reset
}
elseif ($val -lt 0) {
$PSStyle.Foreground.Red + ('{0,5:N2}' -f $val) + $PSStyle.Reset
}
else { '{0,5:N2}' -f $val }
}
So now if I display the table:
$items | Format-Table @{ L = 'a'; E = { color-number $_.a } }, @{ L = 'b'; E = { color-number $_.b } }
it looks like this:
Question
Is this the recommended way to perform conditional formatting of items in a table?
Or is there a better more idiomatic approach?
I'm using PowerShell 7.3.6.