Linked Powershell variables

44 Views Asked by At

Recently, I was faced with a challenge, when I imported an array from JSON to a variable ($Array) as PSCustomObject array, and added it the another variable ($Var). When I modified a property of $Array that property in $Var changed unexpectedly as well. Example for the situation:

$Json = '
[{
    "Property":"a"
}]'

$Array = $Json | ConvertFrom-Json

$Var = $Array[0]

$Var.Property = "b"

When getting the content of $Array, you get 'Property' = 'b' and I cannot find the link among these two variables, so I wonder what I might miss.

I managed to solve this by converting the content of my variable to and from Json:

$Var = $Array[0] | ConvertTo-Json | ConvertFrom-Json

I would be glad if anyone could explain why this is a feature and not a bug. :) Many thanks in advance

0

There are 0 best solutions below