Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Powershell CSV with headers to hashtable

Tags:

powershell

csv

I have a csv file with a header row and I want to convert it to a Hashtable.

For example, this is my input:

#Version1.0
#Fields:ID,Data
1,data1
2,data2
3,data3

I want the output to be a hashtable where Key=ID and Value =Data.

This is what I have, but the results aren't quite what I want.

$mytable = Import-Csv -Path $filePath -Header ID,Data
$HashTable=@{}
foreach($r in $mytable)
{
    $HashTable[$r.ID]=$r.Data
}

This creates my table, but when I output it later via $str = $Hashtable | Out-String Write-Host $str

I'm getting the following:

Name                  Value
--------              -----------
#Fields:ID            Data
1                     data1
2                     data2
3                     data3

How do I get rid of the Headers being written to my hashtable? Is there a more elegant solution than sticking if ($r.ID.StartsWith("#")) { continue; }?

Thanks! -C

like image 824
TeeZee Avatar asked Oct 29 '13 23:10

TeeZee


3 Answers

The default behavior in Import-Csv is to use the first (un-commented) line as the headers. Instead of defining the header in the command, remove "#Fields:" from the header line.

#Version1.0
ID,Data
1,data1
2,data2
3,data3

Then you can create the hashtable like this:

$mytable = Import-Csv -Path $filePath
$HashTable=@{}
foreach($r in $mytable)
{
    $HashTable[$r.ID]=$r.Data
}

Which returns:

Name                           Value
----                           -----
2                              data2
1                              data1
3                              data3
like image 142
llamb Avatar answered Sep 23 '22 00:09

llamb


$HashTable = @{}
Import-Csv $filePath | % { $HashTable[$_.ID] = $_.Data }
like image 43
Greg Avatar answered Sep 23 '22 00:09

Greg


You can try this :

Get-Content $filePath | where {$_ -notmatch '^#'} | ConvertFrom-Csv -Header ID,Data

It remove all the lines begining with # before readingg then as CSV lines.

like image 37
JPBlanc Avatar answered Sep 20 '22 00:09

JPBlanc