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

About the author: Ravikanth C

Ravikanth is the founder and editor of the PowerShell Magazine. He is also a PowerShell MVP who works at Dell Inc. He blogs at http://www.ravichaganti.com/blog and you can follow him on Twitter @ravikanth.

Related Posts

%d bloggers like this: