Michael B Michael B - 3 months ago 15
PowerShell Question

Array object copy updates when object is updated

I have this bit of code

$subnet = @{
name = 'subnet-1'
properties = @{
addressPrefix = '10.0.0.0/24'
}
}

$array = @()

$array += $subnet

$subnet.properties.addressPrefix = '10.1.0.0/24'

$array += $subnet

$array | ConvertTo-Json


Which gives the following output

[
{
"properties": {
"addressPrefix": "10.1.0.0/24"
},
"name": "subnet-1"
},
{
"properties": {
"addressPrefix": "10.1.0.0/24"
},
"name": "subnet-1"
}
]


Why does the hashtable value update in the array after it has been added? I thought that
+=
created a copy of the array.

What is the best way to prevent this? (i.e. get the result I'm looking for!)

Answer

When copying Hash tables, PowerShell uses references, so you need to Clone them to force it to make copies:

$array += $subnet

$subnet2 = $subnet.Clone()
$subnet2.properties = $subnet.properties.Clone()
$subnet2.properties.addressPrefix = '10.1.0.0/24' 

$array += $subnet2

Then the result is:

[
    {
        "properties":  {
                           "addressPrefix":  "10.0.0.0/24"
                       },
        "name":  "subnet-1"
    },
    {
        "properties":  {
                           "addressPrefix":  "10.1.0.0/24"
                       },
        "name":  "subnet-1"
    }
]