Friday, September 29, 2017

Hashtable, export to and import from CSV file

There are built-in functions, "Import-Csv" and "Export-Csv", to handle this request. But it's not as simple as it looks like.

Let's run some test script first.

$csvFile = "E:\test.csv"
$HashTable1 = @{}
$HashTable1.Add("aa", "11")
$HashTable1.Add("bb", "22")
($HashTable1).GetEnumerator() | Sort-Object -Property Value `
| %{new-object psobject -Property @{Value=$_.Value;Name = $_.Name}} `
| Export-Csv $csvFile -NoTypeInformation


$HashTable2 = @{}
$HashTable2.GetType()

$HashTable2 = Import-Csv $csvFile
$HashTable2.GetType()



We can see that we didn't get "HashTable" from "Import-Csv" command. Instead, we got "Array" object.

$HashTable2 = @{}
$Array.Clear()
$HashTable2.Clear()
$Array = Import-Csv $csvFile
$Array | %{$HashTable2.Add($_.Name,$_.Value)}
$HashTable2.GetType()
$HashTable2


That's how we get the HashTable back.

No comments:

Post a Comment