In PowerShell, if I have a list of strings containing versions, "3.0.1.1", "3.2.1.1", etc., how can I sort it the way System.Version would sort it in C#?
To sort the output in the PowerShell you need to use Sort-Object Pipeline cmdlet. In the below example, we will retrieve the output from the Get-Process command and we will sort the, according to memory and CPU usage.
By default, the Sort-Object cmdlet performs an ascending sort—the numbers range from small to large. To perform a descending sort requires utilizing the Descending switch. Note: There is no Ascending switch for the Sort-Object cmdlet because that is the default behavior.
There are actually two ways to do this. The first way to do this is to use the Sort-Object cmdlet (Sort is an alias for the Sort-Object cmdlet). The second way to sort an array is to use the static Sort method from the System.
PS C:\> $ver="3.0.1.1","3.2.1.1"
PS C:\> $ver|%{[System.Version]$_}|sort
Major Minor Build Revision
----- ----- ----- --------
3 0 1 1
3 2 1 1
Just convert it to a Version and sort that way:
$list = "3.0.1.1","3.2.1.1"
$sorted = $list | %{ new-object System.Version ($_) } | sort
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