Powershell Random sort

Here’s a Powershell snippet that randomly sorts the lines in a file. The snippet below reads a text file, called file.txt, located in your user profile directory. The data in the file will be written back with the lines in a different order.

?View Code POWERSHELL
$data = New-Object System.Object;
$data = Get-Content "$Env:USERPROFILE\file.txt";
# Random sort the lines in the file
$data = $data | sort {[System.Guid]::NewGuid()};
Set-Content "$Env:USERPROFILE\file.txt" $data;

If your file started off like this…

file ordered

It will end up looking something like…

file random sort

This is functionally equivalent to…

SELECT *
FROM dbo.Customers
ORDER BY NEWID();

Leave a Reply