Home > database >  import csv as a hashtable with 2 keys
import csv as a hashtable with 2 keys

Time:12-11

I have a table with equal rows and columns

Groups A B C D
A 1 0 0 0
B 0 1 0 0
C 0 0 3 0
D 0 0 1 2

I would like to import it into some type of variable where there output from $h[C].C is equal to 3.

I tired with a simple import command but the formart is giving me trouble to input it into the hashtable. Also is hashtable the best format?

CodePudding user response:

You could use Import-Csv to get an array of PsCustomObjects and convert that to a nested Hashtable like.

I'm using a here-string example, but in real life you would do Import-Csv -Path 'X:\WhereEver\theTable.csv'

$data = @"
Groups,A,B,C,D
A,1,0,0,0
B,0,1,0,0
C,0,0,3,0
D,0,0,1,2
"@ | ConvertFrom-Csv

$h = @{}
$data | ForEach-Object {
    $props = @{}
    $_.PsObject.Properties | Where-Object { $_.Name -ne 'Groups' } | ForEach-Object{ $props[$_.Name] = $_.Value }
    $h[$_.Groups] = $props
}

$h['C'].C  # --> 3
  • Related