简体   繁体   中英

How to index into PSObject Array of Hashtables

I'm working in powershell with an imported CSV. I have a data set like this:

  ID            First_Name                              Last_Nam
--              ----------                              --------
2314             Kenny                                   Anderson
21588            Mark                                    Anderson
2547             Ben                                     Andrews
5797             Benjamin                                Armour

Except with 2000 people and many more columns. Currently the data is stored as a series of hashes in a @{ID = "..",First_Name:"..",Last_Name:".."} and these are stored in a System Object array. I want to store each hash as an index in an array. I want to get the hashtable at that index, but I don't know how to into the System.Object Array. Here's my code:

$csv = import-csv $csv_name 
$row = @(0)*csv.length
$hash = @{}

for($i =0; $i -lt $csv.length; $i++){
$row[$i] += $csv[$i]
}

#error: cannot convert "@{ID : "..", First_Name: "..", Last_Name:".." to Systems.Int32

for($i =0; $i -lt $csv.length; $i++){
$csv[$i].psobject.properties | Foreach { $hash[$_.Name] = $_.Value }

$row[$i]+=$hash
}

#error: Cannot convert systems.collections.hashtable into Systems.Int32

I'm looking for a way to index the array so I can get the hashtable at that index. the The first one, with pointers to the hashtables accessible through the array, is what I think would be the easiest to manipulate. If there's an easier way to get a specific hashtable just from the System.Object[] itself, please tell me.

I should add I don't know the names or amount of the columns in advance.

The return value of Import-Csv is not an array of [hashtable] s, it's an array of [psobject] s, where each column is a property.

There's no need to build any kind of array to get an individual object by index.

$csv = import-csv $csv_name 
$csv[0]
$csv[1].First_Name
# etc

The errors in your code have nothing to do with the question you posed though; you're getting errors trying to add objects to an array, because you're actually trying to add an object or hashtable to an existing array element of type integer.

You don't need to precreate the array with a bunch of zeros, so this line isn't needed:

$row = @(0)*csv.length

Instead, you can create an empty array:

$row = @()

Then, you can just add to the array itself:

$row += $hash

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM