Powershell CSV with headers to hashtable

Question:

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

For example, this is my input:

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.

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

I’m getting the following:

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

Answer:

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.

Then you can create the hashtable like this:

Which returns:

Source:

Powershell CSV with headers to hashtable by licensed under CC BY-SA | With most appropriate answer!

Leave a Reply