There's a simpler and faster way to do this: an array of hashtables. For this, I'll be using an 'ArrayList', which is a type of array that is not a fixed size.
ArrayLists keep PowerShell from having to recreate an array every time you want to add a new item, which is great for foreach operations.
I'm going to go ahead and just present a simple example instead of integrating it into your code. Given the age of this question, it's doubtful you still need it, so this is more for everyone else.
EXAMPLE CODE
# Make sure this is initialized outside BEFORE the foreach loop:
$arr = New-Object Collections.ArrayList
#OR
$arr = [Collections.ArrayList]::new()
# Normally the 'Add' method for ArrayList outputs the updated count,
# setting it to the $null variable prevents that.
$null = $arr.Add( @{foo='bar'} )
$null = $arr.Add( @{foo='test'} )
As for iterating over the resulting array, here are a few good ways of doing so:
PER-ITEM ITERATION
$arr.ForEach({$_.GetEnumerator()}).ForEach({
"Key: " + $ht.Key; "Value: " + $ht.Value })
#OR
foreach ($ht in $arr) {
"Key: " + $ht.Keys; "Value: " + $ht.Values }
output:
Key: foo
Value: bar
Key: foo
Value: test
PER-KEY ITERATION
foreach ($k in ($arr.Keys | Get-Unique)) {
"Key: $k"; "Value(s): " + $arr.$k }
output:
Key: foo
Value(s): bar test
I'm deliberately avoiding using ForEach-Object in these examples due to its performance issues in every version of PowerShell (7.2.1 is the current version as of writing). You can read more about that here.