I was going nuts trying to sort an array into a random order. I was hoping for something in PowerShell that would be along the lines of Shuffle() in PHP or Ruby.
In fact, after looking at it I was a little surprised at all of the things that an array can’t do in PowerShell.
But that’s ok – it turns out to be really easy and if you’re thinking that you need to learn a different language to shuffle an array in PowerShell you’re dead wrong.
It’s super easy to randomize the order of an array in PowerShell – you just have to simplify and think about it in a different way.
#Give me a list - any list will do. Here's 26 numbers. $MyList = 0..25 #Shuffle your array content but keep them in the same array $MyList = $MyList | Sort-Object {Get-Random} #Randomize the contents of your array and save them into a new array $MyShuffledList = $MyList | Sort-Object {Get-Random}
This is so easy it defies belief. Why does it work?
Since the Sort-Object can accept pipeline input, it’s often used to organize the contents of a list based on one property or another. You’ve probably used it for sorting by names, or for sorting files by their size. But a magical thing happens when you tell it to not sort by a specific property but instead pass it a scriptblock.
For each object that is passed into Sort-Object through the pipeline the scriptblock is called. And since Get-Random evaluates to a rather large random number – the objects in the array are sorted based on all of those random integers.
I know this was an eye-opener for me, and I really like doing it this way. Before coming across the sort method I tried going through each item in the array and adding a noteproperty to it. Which worked since I was using an array of objects anyway but was way clunkier than doing it this way.
Leave any questions or feedback in the comments and do me a favor and hit the like button on my facebook page for me, ok? Thanks!