Why cant I store a hashtable in an arraylist? Why cant I store a hashtable in an arraylist? powershell powershell

Why cant I store a hashtable in an arraylist?


Hashtables are references, when you create one object all further operations are against that one hashtable, including trying to retrieve that information.

You can declate a new hashtable each run of the loop to get around this.

$allTests = New-Object System.Collections.ArrayList1..10 | foreach {    $singleTest = @{}    $singleTest.add("Type", "Human")    $singleTest.add("Count", $_)    $singleTest.add("Name", "FooBar...whatever..$_")    $singleTest.add("Age", $_)    $allTests.Add($singleTest) | Out-Null}

or even this to cut out some bloat.

$allTests = New-Object System.Collections.ArrayList1..10 | foreach {    $allTests.Add(@{        Type = "Human"        Count = $_        Name = "FooBar...Whatever..$_"        Age = $_    }) | Out-Null}

Both of these answers will give you the expected output.


@ConnorLSW's answer is spot on functionally.

I have another solution for you that gives you more flexibility. I find myself building custom objects that share some fields so instead of making new objects every run of the loop you could define the base object outside the loop just as you are now and then inside the loop you can change a property value for that instance and then add it to your collection like this:

$allTests.Add($singleTest.Psobject.Copy())

This copys the contents to a new object before inserting it. Now you are not referencing the same object as you are changing during the next iteration of the loop.


Since hash tables are passed by reference, you're just adding multiple references to the same hash table to your arraylist. You need to create a new copy of the hash table and then add that to your array list.

One option is to use the hash table .clone() method when you want to save a copy to the arraylist.

$allTests.Add($singleTest.clone()) | out-null