按多个属性对对象排序

时间:2015-07-23 20:42:24

标签: powershell

我正在尝试使用PowerShell对表示应用程序版本的对象进行排序

$versionsObjects = @{
    Major = 3
    Minor = 2
    Bugfix = 1
},
@{
    Major = 3
    Minor = 5
    Bugfix = 1
},
@{
    Major = 1
    Minor = 2
    Bugfix = 1
},
@{
    Major = 4
    Minor = 2
    Bugfix = 1
}

$sortedVersions = ($versionsObjects | Sort-Object -Property @{Expression="Major"; Descending=$true}, @{Expression="Minor" ;Descending=$true}, @{Expression="Bugfix"; Descending=$true})
$sortedVersions | %{echo ( "{0}.{1}.{2}" -f $_.Major, $_.Minor, $_.Bugfix)}

输出与输入的顺序相同:

3.2.1
3.5.1
1.2.1
4.2.1

但它应该是

4.2.1
3.5.1
3.2.1
1.2.1

我做错了什么?

3 个答案:

答案 0 :(得分:4)

如果你至少在powershell v3.0中,你可以这样做:

$versionsObjects = [ordered]@{
    Major = 3
    Minor = 2
    Bugfix = 1
},
[ordered]@{
    Major = 3
    Minor = 5
    Bugfix = 1
},
[ordered]@{
    Major = 1
    Minor = 2
    Bugfix = 1
},
[ordered]@{
    Major = 4
    Minor = 2
    Bugfix = 1
}

$versionsObjects | % { $_.values  -join '.' } | sort -Descending {[version]$_ }

或所有版本:

$versionsObjects = @{
    Major = 3
    Minor = 2
    Bugfix = 1
},
@{
    Major = 3
    Minor = 5
    Bugfix = 1
},
@{
    Major = 1
    Minor = 2
    Bugfix = 1
},
@{
    Major = 4
    Minor = 2
    Bugfix = 1
}

$versionsObjects | % { $_.Major,$_.Minor,$_.bugfix  -join '.' } | sort -Descending {[version]$_ }

答案 1 :(得分:3)

你的表达方式不是很正确。尝试使用Sort-Object部分:

Sort-Object -Property @{Expression={$_.Major}; Descending=$true}, @{Expression={$_.Minor} ;Descending=$true}, @{Expression={$_.Bugfix}; Descending=$true})

答案 2 :(得分:0)

我无法使用哈希表工作,但是当我使用自定义PSObject进行排序时,我获得了成功。也许它会有所帮助?

$versionsObjects = @()

$versionsObjects += New-Object -TypeName PSObject -Property @{Major = 3; Minor = 2 ; Bugfix = 1}
$versionsObjects += New-Object -TypeName PSObject -Property @{Major = 3; Minor = 5 ; Bugfix = 1}
$versionsObjects += New-Object -TypeName PSObject -Property @{Major = 1; Minor = 2 ; Bugfix = 1}
$versionsObjects += New-Object -TypeName PSObject -Property @{Major = 4; Minor = 2 ; Bugfix = 1}


$versionsObjects |

Sort-Object -Property Major,Minor,Bugfix -Descending |

ForEach-Object -Process {

echo ( "{0}.{1}.{2}" -f $_.Major, $_.Minor, $_.Bugfix)

                    }