PowerShell - Random Color

2012, Feb 15    

Just messing around here, but thought others might want to know how to randomly (or intelligently) grab a color.  There’s basically three parts to this process.

  1. Get the number of colors.
  2. Grab a random color.
  3. Apply the color.

I’ve done the above three steps in these three lines of code …

$max = [System.ConsoleColor].GetFields().Count - 1
$color = [System.ConsoleColor](Get-Random -Min 0 -Max $max)
Write-Host -Fore $color 'lolz'

If you want the one liner version …

Write-Host -Fore ([System.ConsoleColor](Get-Random -Min 0 -Max ([System.ConsoleColor].GetFields().Count - 1))) 'lolz'

Want a list of colors?

[System.ConsoleColor].GetFields() | %{$_.Name}

The first thing returned value__ is just metadata and won’t be randomly selected in the range we’ve specified.  If we randomly get 0, Black is returned.  If we randomly get 15, White is returned.

Note:  As of the time of this writing, .Count-1 from the above code equals 16.  Get-Random’s -Maximum parameter “returns a value that is less than the maximum (not equal).”  Thus, our inclusive range is 0 through 15.

Hope this helps others out there.  Cheers!