#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!

Share on: