PowerShell to Sort Contents of Each File in Directory (Recursively)

We were receiving some files of data that was not sorted, and needed to be able to do a side-by-side compare of two files. Two files could have the same data values, but might not be in the same order. Without the data being sorted, the compare was basically impossible.


cls
#
#       Author: Neal Walters (http://MyLifeIsMyMessage.net) 
#         Date: 05/05/2022
#  Description: Make copy of all files in directory, sort them each by contents, 
#               retaining the original date/times on the file. 

$fromDir = "C:\Data\YourDir" 
$toDir   = "C:\Data\YourDirSorted" 

# make a copy so we don't change "in place" and risk messing up the original files 
# this handles making all the directories for us 
robocopy $fromDir $toDir  *.* /s

$files = get-childitem $toDir -recurse 

foreach ($file in $files) 
{
   write-Host "file=$($file.Name)" 
   $holdCreationTime  = $file.CreationTime
   $holdLastWriteTime = $file.LastWriteTime
   $sortedContents = get-content -Path $file.FullName | sort-object 
   set-content -Path $file.FullName $sortedContents 
   $file.CreationTime = $holdCreationTime 
   $file.LastWriteTime = $holdLastWriteTime 
}

Leave a Reply