PowerShell – Random Color

VertigoRay/ February 15, 2012/ Uncategorized/ 0 comments

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!

Leave a Comment

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>