Question:
How would you sort this filename list with PowerShell so they will appear in descending version order?
I only need the highest version filename.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
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.
1 2 3 4 |
$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.
1 2 3 4 |
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.
Answer:
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):
1 2 3 4 5 6 7 8 9 10 |
dir $_ | Sort-Object { [Version] $(if ($_.BaseName -match "(\d+_){3}\d+") { $matches[0] -replace "_", "." } else { "0.0.0.0" }) } | select -last 1 -ExpandProperty Name |