saktas saktas - 3 months ago 49
PowerShell Question

Sorting according to version numbers in PowerShell

I am sorting the folders in a directory according to version numbers and removing the old ones.
The problem I am having is thanks to octopus deploy's versioning standard. If you release a project with the same version multiple times, the numbers will look like this;




1.3.5.6
1.3.5.6_1
1.3.5.6_2
1.3.5.7





And those underscores are killing my algorithm. My function as follows;

function CleanUp-Files ($col,$NumberToSave) {
foreach ($pkg in $col.FullName) {
Get-ChildItem -Path $pkg |
Where-Object {$_.PsIscontainer} |
Sort-Object { [version]($_.Name -replace '^(\d+(\.\d+){1,3})(_\d{1,2})?$', '$1') } -Descending |
Select-Object -Skip $NumberToSave |
Remove-Item -Recurse -Force -Verbose
}
}


What can I do to accommodate those underscores into my sorting?

Answer

Sort-Object can execute on more than one argument.

Sort-Object { [Version]($_ -replace '_.*$') }, { if ($_ -match '_') { [Int]($_ -replace '^.*_') } else { 0 } }