简体   繁体   English

在PowerShell中根据版本号排序

[英]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. 我遇到的问题是由于octopus deploy的版本控制标准。 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? 我该怎么做才能将这些下划线容纳到我的排序中?

排序对象可以对多个参数执行。

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

Split the Name property by _ - output the first part as a [version] object first, then the suffix last: _分隔Name属性-首先将第一部分输出为[version]对象,然后最后输出后缀:

... |Sort-Object { 
        $version,$suffix = $_.Name -split '_'
        $version -as [version]
        if($suffix){$suffix} 
}

I would multiply the revision with 100 and add the number after the underscore: 我会将修订版本乘以100,然后在下划线后面加上数字:

function CleanUp-Files ($col,$NumberToSave) {
    $rex = [regex]'(.*\.)(\d+)_?(\d+)?'
    $callback = {  
        param($match) 
        '{0}{1}' -f $match.Groups[1].Value , ([int]$match.Groups[2].Value * 100 +[int]$match.Groups[3].Value) 
        }
  foreach ($pkg in $col.FullName) {
    Get-ChildItem -Path $pkg |
    Where-Object {$_.PsIscontainer} |
    Sort-Object { [version]($rex.Replace($_.Name, $callback)) } -Descending |
    Select-Object -Skip $NumberToSave |
    Remove-Item -Recurse -Force -Verbose
  }
}

A simple demo: 一个简单的演示:

$versions = '1.3.5.6', '1.3.5.6_1', '1.3.5.6_2', '1.3.5.7'

$rex = [regex]'(.*\.)(\d+)_?(\d+)?'
$callback = {  
    param($match) 
    '{0}{1}' -f $match.Groups[1].Value , ([int]$match.Groups[2].Value * 100 +[int]$match.Groups[3].Value) 
    }

$versions | ForEach-Object {
    [version]($rex.Replace($_, $callback))
}

will give you: 会给你:

Major  Minor  Build  Revision
-----  -----  -----  --------
1      3      5      600     
1      3      5      601     
1      3      5      602     
1      3      5      700     

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM