0

I have an array in Powershell with the following rows: 1,Tgt,10,Fld 2,XM,8,Fi 3,TX,12,Fi

First column is the row counter, second column is a filter type, 3rd column is a count, 4th column is an Action Type.

I need to create a hash table of the 2nd & 3rd columns.

When I do the following in Powershell, it creates a hash table I can use.

$z=@()
$z = {
Tgt = 10
XM = 8
TX = 12
}

But, if I use a foreach to attempt to do the same thing, it creates a collection of the collection.

foreach ($b in $arr) {
   $z2 += @{$b[1] = $b[2]}
   }

Each has 3 elements in it, but the hash table $z is a {System.Collections.DictionaryEntry,System.Collections.DictionaryEntry,System.Collections.DictionaryEntry}

while hash table $z2 is a

{{System.Collections.DictionaryEntry},{System.Collections.DictionaryEntry},{System.Collections.DictionaryEntry}}

$z can be referenced in a foreach by using the $z.Keys, but I can't reference the same thing on $z2. Even though each has 3 rows, $z is an array of 3 rows, but $z2 is an array of 3 arrays of 1 row each. What I want to do is to have $z and $z2 hash table be identical to each other in every way.

I'm sure I am doing something obvious & wrong trying to create this hash table from the existing array, but cannot figure out what I'm doing wrong. Any suggestions appreciated.

Thanks!

1 Answer 1

3

You don't show where you are initializing $z2, but with this line:

$z2 += @{$b[1] = $b[2]}

you are creating a new hashtable with a single entry (key $b[1] and value $b[2]) and adding it to $z2.

Instead, try using:

$z2[$b[1]] = $b[2]

To create an empty hashtable, use @{}, instead of @() which makes an array.

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

1 Comment

The combination of both things (I didn't catch the bracket vs parenthesis) and the $z2[$b[1]] fixed my problem. Thank you very much for the assistance!

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.