Get random element of an array using Powershell

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.

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?

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

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.

 

Comments

  1. With the 2003 End of Life counter in the right sidebar, I think it’s safe to assume everyone is running v3 or higher now. Thanks for the tip though!

Leave a Reply