Friday, May 22, 2015

PowerShell Random Sort a List

Maybe you have a list that you want to put in a random order.  I had a list of words that I wanted shuffled without repeating.  At first, I was thinking that I'd have to devise some way of choosing at random without replacement, so that Get-Random wouldn't choose the same word twice.

Then I found that Get-Random has a -Count parameter, so I thought: could I make the count the same as the number of items on my list?

Of course!  Why did I even question?
"Mercury" , "Venus" , "Earth" , "Mars" , "Jupiter" , "Saturn" , "Uranus" , "Neptune" , "Pluto" | Get-Random  -Count  9

However, I did learn that the count cannot exceed the length of the list.  If it does, PowerShell won't complain; it will just stop when it has listed every item once. 

No comments:

Post a Comment