How to use a natural sort in PowerShell

 
 
  • Gérald Barré

PowerShell has no built-in natural sort, but you can achieve one using the Sort-Object cmdlet with a custom script block.

#What is a natural sort?

A natural sort is a sorting algorithm that orders strings in a human-friendly way. For example, a natural sort of the following strings:

  1. file1.txt
  2. file10.txt
  3. file2.txt

would be:

  1. file1.txt
  2. file2.txt
  3. file10.txt

The natural sort treats embedded numbers by their numeric value rather than by lexicographic character order.

#How to use a natural sort in PowerShell?

Use Sort-Object with a custom script block that returns a transformed value for comparison. A regular expression finds each numeric substring and pads it with leading spaces so numbers compare in the correct order. For example, file1.txt becomes file + (padded 1) + .txt. Adjust the padding length as needed for your data.

PowerShell
Get-ChildItem | Sort-Object { [regex]::Replace($_.Name, '\d+', { $args[0].Value.PadLeft(100) }) }

Do you have a question or a suggestion about this post? Contact me!

Follow me:
Enjoy this blog?