How to use a natural sort in PowerShell

 
 
  • Gérald Barré

PowerShell doesn't provide a built-in way to use a natural sort. However, you can use the Sort-Object cmdlet with a custom script block to achieve a natural sort. In this post, I describe how you can use a natural sort in PowerShell.

#What is a natural sort?

A natural sort is a sorting algorithm that orders strings in a way that is more human-friendly. 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

You can see that the natural sort orders the strings based on the numeric value of the numbers in the string, rather than the lexicographic order of the characters.

#How to use a natural sort in PowerShell?

A simple way to use a natural sort in PowerShell is to use the Sort-Object cmdlet with a custom script block. The script block should return the value that you want to sort by. In this case, you can use a regular expression to extract the numeric value from the string and pad it with zeros to ensure that the numbers are sorted correctly. For instance, the string file1.txt would be transformed into file00001.txt. You can use as much padding as you need to ensure that the numbers are sorted correctly.

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?Buy Me A Coffee💖 Sponsor on GitHub