问题
I have an array with decimal numbers like this:
reihenfolge ########### 100000.00001 1000000.00001 101000.00001 101010.00001 101020.10001
If I sort it without parameters I get the order above. I would expect that the second number is the last entry. I also tried to sort as int or as version or with regex, but until now I didn't find the way I expect.
$script:array = $script:array | Sort-Object reihenfolge
$script:array = $script:array | Sort-Object { [regex]::Replace($_.reihenfolge, '\d+', { $args[0].Value.PadLeft(20) }) }
$script:array = $script:array | Sort-Object { $_.reihenfolge -as [version] }
$script:array = $script:array | Sort-Object { $_.reihenfolge -as [int] }
回答1:
It looks like you are reading the array from a text or csv file. In that case, the numbers are actually strings, not numbers. In order to sort numeric, try below:
1) If your array comes from a textfile, INCLUDING the lines reihenfolge
and ###########
use the Get-Content
cmdlet:
$array = Get-Content -Path 'D:\blah.txt' | Select-Object -Skip 2 | Sort-Object @{Expression = { [double]$_ }}
$array
2) If your data comes from a CSV file with a column named reihenfolge
, do this:
$array = (Import-Csv -Path 'D:\blah.txt').reihenfolge | Sort-Object @{Expression = { [double]$_ }}
$array
Both will return the array sorted like this:
100000.00001 101000.00001 101010.00001 101020.10001 1000000.00001
来源:https://stackoverflow.com/questions/57991756/powershell-sorting-problem-of-decimal-numbers