Sorting of data with Export-CSV in PowerShell
One of the most annoying things when using the Export-CSV
cmdlet in PowerShell is that the data is never in the order you stored it in. This article solves this problem and changes your life in the process!
In a lot of my scripts I use PSObject
to store key, value data for enumerated objects. I then store each of these PSObjects in an array. Finally I export the array to CSV using Export-CSV
.
Every time I do this, I always end up with the same problem – the data exported in the CSV file is never in the order I stored it in the PSObject
.
The reason why this happens is actually because of a limitation with the PSObject
PowerShell object. This was actually solved in PowerShell 3.0 (and consequently all version after 3.0).
Implementing the fix is simply through the way you define the PSObject
in the first place. The examples below explain what I mean:
PowerShell 2.0
This is how you create a PSObject in PowerShell 2.0. This method DOES NOT allow for sorting of data with Export-CSV.
$MyPSObject = New-Object -TypeName psobject -Property @{
Key1 = 'Value1'
Key2 = 'Value2'
}
$aResults += $MyPSObject
PowerShell 3.0 and above
Creating a PSObject in the following way allows for the sorting of data with Export-CSV. In other words, the data is exported in the order that you have added it to the PSObject
.
$MyPSObject = [PSCustomObject]@{
Key1 = 'Value1'
Key2 = 'Value2'
}
$aResults += $MyPSObject
In the second example, when exporting the $aResults
array, the data within the CSV file will be presented in order (i.e. Key 1 first and then Key 2). Whereas, in the first example, the exported data will most likely be Key 2 and then Key 1.
What is PSObject?
If you are unfamiliar with the PowerShell PSObject, then have a look at this article in which I explain in detail what, when and where to use PSObject
– Using PSObject to store data in PowerShell.
You can now enjoy the sorting of data with Export-CSV in PowerShell! Enjoy!
Well, I’m using PS 5.0 in Win 10 and I’m having the same issues as PS2 I have a sorted array, showing properly sorted in the console, but when I Export-CSV, and open the file its no longer sorted.