Get Random Lines From A File (Or Random Files From A Directory… Or Random Item From Any Collection)

Don’t ask me why but I recently had a need to get a random line from a text file. There’s a small piece of strange behavior that I came across with the cmdlet I chose to use: Get-RandomGet-Random does what it sounds like. It’s commonly used for getting random numbers (see this post I wrote a while ago about a gotcha with this behavior) but you can also pass it an input object.

For this example, I have a file in my c:\temp folder named random.txt. It’s contents just look like this.

So since Get-Random includes an -InputObject parameter, I should just be able to do the following, right?

Well, if you were hoping it would be that easy, I’m afraid I’ve got some bad news. Every time you run this command, the InputObject specified is always the value returned.


Well that’s not very helpful for a guy looking for a random line from the file. Turns out that -InputObject is looking for a collection of items, it’s not doing the work of examining the path to the file and extracting the data from it. That’s easy enough to get around. We’ll just do that work ourselves.

There we go. Get a random item from the collection returned by Get-Content C:\Temp\Random.txt. Then you get output like this.


You could get a random file from a directory like this.

Or, indeed, pass any array or hash table. Here’s an example of getting a random property from the $Host variable.





Leave a Reply

Your email address will not be published. Required fields are marked *