Import-CSV and Types

by Aug 20, 2009

Export-CSV and Import-CSV are great ways of persisting data in a structured way. There are some limitations, though. Take a look. This line saves a folder listing to a csv file:

Dir $env:windir | Select-Object Name, Length | Export-CSV $home\test.csv

You can later reload it into a variable using this line:

$result = Import-CSV $home\test.csv

When you output $result, you get back the same structured information: PowerShell keeps object properties. However, this is not entirely true. When you try and sort the result by Length, you are up for a surprise:

$result | Sort-Object Length

Apparently, PowerShell now sorts alphabetically rather than numerical. As it turns out, Export/Import-CSV does preserve properties but converts them all to string.

Twitter This Tip! ReTweet this Tip!