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') } 
    

    [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.