Search code examples
powershellsortingpowershell-2.0powershell-3.0version-sort

Sorting of files based on version number in the middle of the file name


I am new to the power shell. I am trying to sort a list of files which are having version number in the middle of the name.

Here is the list of files :

sample-file-1.1.0-patch.zip
sample-file-1.1.1-patch.zip
sample-file-1.1.2-patch.zip
sample-file-1.1.2.1-fix-patch.zip
sample-file-1.1.3-patch.zip
sample-file-1.1.3.1-fix-patch.zip
..
sample-file-1.1.15-patch.zip
sample-file-1.1.15.1-fix-patch.zip
sample-file-1.1.15.2-fix-patch.zip
..
sample-file-2.0.0-patch.zip
sample-file-2.0.1-patch.zip
..

I would request you to help me with the sorting logic.

Thanks


Solution

  • The simplest approach with your sample input is the following, which assumes that the first digit following - starts the version number and that it ends with the last digit before a subsequent -:

    Get-ChildItem *.zip | Sort-Object { [version]($_.Name -replace '^[^\d]+-(.*\d)-.*', '$1') } 
    
    • $_.Name -replace '^[^\d]+-(.*\d)-.*', '$1' extracts the version number from each file name as a string.

    • [version] casts that string to a version-number object (System.Version)[1] , which is sortable based on the version-number components.

    • Passing the whole expression as a script block { ... } to Sort-Object means that sorting is based on the [version] instances returned by the script block, evaluated for each input filename.


    [1] PSv5.1 introduced a related type, [System.Management.Automation.SemanticVersion], based on semantic versioning, which wouldn't work here, however, because it only supports 3 version-number components.