I needed to return a random element of an array using powershell. I have used this method while building simple wireless passwords for a company. This is a simplified version, first lets create the array with Blue and Green in it.

$array = 'Blue','Green'

How do I access the array then, simple just do $array[$x] where $x is random. So how do we get a valid integer as $x?

Get-Random -Maximum $array.count

Lets just make sure that we are working with an array and not just a string, cast the array variable as array [array]$array.

The end result

$array = 'Blue','Green'
$array[(Get-Random -Maximum ([array]$array).count)]

Why complicate with [array]

Q: I simplified the command by removing the ([array]), and it still works. So why did you add that extra?

A: If you or your friends are running an older powershell version (2 or less), they you cant run .count on a string. If you try it, it will return nothing.