I'm trying to programmatically combine an unknown number of hashtables into a larger hashtable. Each individual table will have the same keys. I tried just appending it, but it throws an error about duplicate keys.
ForEach ($Thing in $Things){
$ht1 = New-Object psobject @{
Path = $Thing.path
Name = $Thing.name
}
$ht2 += $ht1
}
That throws the error
Item has already been added. Key in dictionary: 'Path' Key being added: 'Path'
The end result would be that later I can say
ForEach ($Item in $ht2){
write-host $Item.path
write-host $Item.name
}
Converting my comment to an answer.
What you probably want to create is an array of hashtables. Each item in the array can have its own value for each key. This structure can be used in the way you indicate in your query at the end of your post.
Try this:
$things = gci $home
$ht2 = @() # create empty array
ForEach ($Thing in $Things){
$ht1 = New-Object psobject @{
Path = $Thing.PSpath
Name = $Thing.name
}
$ht2 += $ht1
}
$ht2
Note that I changed .path to .PSpath in order to make the example work. Note that $ht2 gets initialized to an empty array before looping.