saktas saktas - 8 months ago 111
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;

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?


Sort-Object can execute on more than one argument.

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