PowerShell Import-CSV and Sort-Object

Recently I noticed that when I was sorting data imported from a CSV file, the behaviour wasn’t quite as expected.
[ps collapse="false" firstline="1" gutter="false" highlight="" tabsize="4" toolbar="false"]
$scores = Import-Csv .\scores.csv
$scores | Sort-Object -Property Score -Descending
[/ps]

sort-object

sort-object


I’m pretty sure Julie’s score of 300 should be higher then Homer’s!

[ps collapse="false" firstline="1" gutter="false" highlight="" tabsize="4" toolbar="false"]
$scores | Get-Member
[/ps]

sort-object example 2

sort-object example 2


A quick look shows that even though the score is a number it’s being treated as a system.string. To resovle this we need to change it back to a number. This is done by wrapping it into a code block and recasting as an integar:
[ps collapse="false" firstline="1" gutter="false" highlight="" tabsize="4" toolbar="false"]
$scores | Sort-Object -Property {[int] $_.Score} -Descending
[/ps]
sort-object example 3

sort-object example 3


Fixed! More information can be found in this Hey,Scripting Guy Article.

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>