4

#PSTip Get a random item from an enumeration

Note: This tip requires PowerShell 2.0 or above.

In an earlier tip, I showed you how to get the item count in an enumeration. In this tip, we shall see how to retrieve a random item from an enumeration.

Add-Type -AssemblyName System.Drawing
$count = [Enum]::GetValues([System.Drawing.KnownColor]).Count
[System.Drawing.KnownColor](Get-Random -Minimum 1 -Maximum $count)

Simple!

Filed in: Columns, Tips and Tricks Tags: ,
  • http://twitter.com/sstranger Stefan Stranger

    Hi Ravi,

    Maybe you should add the Add-Type -AssemblyName System.Drawing line to your exampels.
    /Stefan

    • http://www.ravichaganti.com/blog Ravikanth

      Hey Stefan, Add-Type is required only for 2.0 and that is the reason I marked this tip as 3.0 and above. Anyway, this is a good suggestion. I will update both tips to reflect this fact.

  • http://twitter.com/sstranger Stefan Stranger

    Hi Ravi,

    You can also use the FromKnowColor to convert the color to RGB values.

    $count = [Enum]::GetValues([System.Drawing.KnownColor]).Count

    $randomcolor

    = [System.Drawing.KnownColor](Get-Random -Minimum 1 -Maximum $count)

    [

    System.Drawing.Color]::FromKnownColor($randomcolor)

    • http://www.ravichaganti.com/blog Ravikanth

      Thanks Stefan. Yes, this is how I am using this with my Blink(1) :)

© 2013 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.