0

I import a CSV file containing a primary key and some data, for example

key,data
1,one
2,two
3,three
4,four
5,five

I want the data field of one record, based on the key value. here's what I do

$db=import-csv data.csv
$data=($db|?{$_.key -eq 4}).data

is there a smarter/more elegant way to write the second line ?

PS. for this time, I'm stuck with PS v2

2 Answers 2

1

There is more elegant way, not sure about performance though:

# Convert CSV to Hashtable
$db = Import-CSV data.csv | Group-Object -AsHashTable -AsString -Property Key

You can then get values like this:

  • PS 2.0: $($db.4).Data

  • PS 3.0 and higher: ($db.4).Data

More details: Turning CSV-Files into "Databases"

Sign up to request clarification or add additional context in comments.

Comments

0

If you know that the keys are ascending, without gaps, and start from 1, then you could go by index (zero based):

$desiredKey = 4
$db[$desiredKey-1].data

But that seems like a dicey assumption, and the way you're doing it is probably better than that.

You could build a [hashtable] and then do direct lookups:

$hash = @{}
$db | ForEach-Object { $hash[$_.key] = $_.data }

$db[4]

1 Comment

unfortunately the keys set contains a lot of holes. I'll go with the hash table.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.