Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell, Sort a list of files by version number at the end of the filename?

Tags:

powershell

How would you sort this filename list with PowerShell so they will appear in descending version order?

I only need the highest version filename.

Name
----
CYFS_PreK_1_0_1_10
CYFS_PreK_1_0_1_11
CYFS_PreK_1_0_1_12
CYFS_PreK_1_0_1_13
CYFS_PreK_1_0_1_14
CYFS_PreK_1_0_1_15
CYFS_PreK_1_0_1_16
CYFS_PreK_1_0_1_17
CYFS_PreK_1_0_1_18
CYFS_PreK_1_0_1_19
CYFS_PreK_1_0_1_20
CYFS_PreK_1_0_1_21
CYFS_PreK_1_0_1_22
CYFS_PreK_1_0_1_23
CYFS_PreK_1_0_1_8
CYFS_PreK_1_0_1_9

The following will select "CYFS_PreK_1_0_1_9" since it is the highest number alphabetically as there are no leading zeros in the version numbers.

$lastVersion = get-childitem $src |
    sort-object -descending | 
    select-object -First 1 -Property:Name

However, I am looking for "CYFS_PreK_1_0_1_23"

UPDATE:

If we only care about the final set of numbers, we can split the name for underscores and sort the final segment numerically.

Get-ChildItem $_ | 
    Sort-Object {[int] $_.Name.Split("_")[5]} -Descending |
    select-object -First 1 -Property:Name

This works for this set, however, if we rev to version 1_0_2_x, then it breaks again as the final 1 in 1_0_2_1 is less than 23 in 1_0_1_23.

like image 544
Dan Sorensen Avatar asked Jul 29 '14 23:07

Dan Sorensen


1 Answers

You can use the [Version] type to do the version sorting. This only takes the version into account (so it doesn't care about the beginning of the filename):

dir $_ |
    Sort-Object { 
        [Version] $(if ($_.BaseName -match "(\d+_){3}\d+") { 
                        $matches[0] -replace "_", "."
                    } 
                    else { 
                        "0.0.0.0"
                    })  
    } | select -last 1 -ExpandProperty Name
like image 180
Rohn Edwards Avatar answered Sep 30 '22 15:09

Rohn Edwards