5

#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: ,

5 Responses to "#PSTip Get a random item from an enumeration"

  1. Hi Ravi,

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

    • Ravikanth says:

      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.

  2. 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)

  3. Josh says:

    Another option that lets you do this in a single line (useful if you’re using a subexpression in a string) is to use the second form of Get-Random which takes pipeline input.

    [Enum]::GetValues([ConsoleColor]) | Get-Random

Leave a Reply

Submit Comment

© 2016 PowerShell Magazine. All rights reserved. XHTML / CSS Valid.
Proudly designed by Theme Junkie.
%d bloggers like this: