I'm trying to use PowerShell for sorting objects representing application verions
$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)}
The output is in the same order as input:
3.2.1
3.5.1
1.2.1
4.2.1
But it should be
4.2.1
3.5.1
3.2.1
1.2.1
What am I doing wrong?
Example 1: Sort Array by Property NameThe sort() method sorts its elements according to the values returned by a custom sort function ( compareName in this case). Here, The property names are changed to uppercase using the toUpperCase() method. If comparing two names results in 1, then their order is changed.
Sorting array of objectsArrays of objects can be sorted by comparing the value of one of their properties.
Your expressions aren't quite right. Try this for the Sort-Object part:
Sort-Object -Property @{Expression={$_.Major}; Descending=$true}, @{Expression={$_.Minor} ;Descending=$true}, @{Expression={$_.Bugfix}; Descending=$true})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With