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. 

Get-Date -format

I used to do it the long way, gathering the minute, hour or the day, month, year.  Then I learned about -format, and it changed everything and made the code much shorter.

Get-Date -Format "yyyyMMdd"
20150522
Get-Date -Format "MM-dd-yy"
05-22-15

See: http://technet.microsoft.com/en-us/library/ee692801.aspx