This week we are looking at enumerations: what they are, and how you can benefit from them.
In the previous tips, we explored how enumerations work. You may remember how we changed the console foreground color:
PS> $host.UI.RawUI.ForegroundColor = 'Red' PS> $host.UI.RawUI.ForegroundColor = 'White' PS>
These commands change the foreground color first to red, then back to white. The string color names were internally translated to the expected System.ConsoleColor enumeration value.
Most enumerations are just an easy way of labelling numeric values. The values “Red” and “White” are really integer numbers:
PS> [int][System.ConsoleColor]'Red' 12 PS> [int][System.ConsoleColor]'White' 15
So if you know the numbers, you could use them as well:
PS> $host.UI.RawUI.ForegroundColor = 12 PS> $host.UI.RawUI.ForegroundColor = 15
Of course, it immediately becomes evident how much harder would be to read code like this. Still, there is a use case. If you’d like to set random colors for your console, you could use numeric values. There are 16 available console colors, so this would re-colorize your console with a random background and foreground color:
$background, $foreground = 0..15 | Get-Random -Count 2 $host.UI.RawUI.BackgroundColor = $background $host.UI.RawUI.ForegroundColor = $foreground