I am trying to sort a colomn with numbers in a CSV file. But somehow it doesn't work. Sample CSV:
Orange;65
Red;160
Green;140
White;110
Purple;85
This is the piece of code I tried it with:
$csv = Import-Csv -Header "Color", "Number" -delimiter ';' data.csv
$csv | Sort-Object Number
Which gives me the following output:
Color Number
----- ------
White 110
Green 140
Red 160
Orange 65
Purple 85
Obviously not in the correct order. Can someone please explain me how to resolve this issue?
An Object is an unordered collection of properties. The answers below show you how to "use" sorted properties, using the help of arrays, but never actually alter the order of properties of objects themselves.
Sort an Array of Objects in JavaScriptTo sort an array of objects, you use the sort() method and provide a comparison function that determines the order of objects.
For example, with a hash table you can sort one property in ascending order and another property in descending order. To sort objects, send them down the pipeline to Sort-Object . If you use the InputObject parameter to submit a collection of items, Sort-Object receives one object that represents the collection.
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.
Import-CSV
imports csv columns as strings
by default. You need to cast it to int
before you can sort by value, and not "alphabetical". Ex:
$csv = Import-Csv -Header "Color", "Number" -delimiter ';' data.csv
$csv | % { $_.Number = [int]$_.Number }
$csv | Sort-Object Number
Color Number
----- ------
Orange 65
Purple 85
White 110
Green 140
Red 160
As an alternative, you can cast it while sorting, like this:
$csv = Import-Csv -Header "Color", "Number" -delimiter ';' data.csv
$csv | Sort-Object @{e={$_.Number -as [int]}}
or even shorter $csv | Sort-Object { [int]$_.Number }
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