Peyre
Peyre

Reputation: 573

powershell - select an object from an object array

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

Upvotes: 0

Views: 776

Answers (2)

beatcracker
beatcracker

Reputation: 6930

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"

Upvotes: 1

briantist
briantist

Reputation: 47872

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]

Upvotes: 0

Related Questions