1

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

Mathias R. Jessen
  • 157,619
  • 12
  • 148
  • 206
  • 3
    This is expected. Setting a variable to a psobject creates a reference to the same object. It is not a clone or copy. When you convert the object to Json and back to object, it is now a different object – AdminOfThings Sep 25 '20 at 03:57
  • Thanks for the clarification. Would you suggest a more sophisticated way to make a copy of the object itself? I do not feel that converting to and from Json is the nicest solution. In my original script I use Json files as a template of data, which one I put into a variable, modify the content of it using a function and add the result to a variable with +=. I tried to convert the type of the object from PSObject to Collection as well, but it did not bring the expected result. – Peter Lukacs Sep 25 '20 at 04:21
  • For cloning objects, have a look [here](https://stackoverflow.com/questions/57833377/changes-to-var2-also-change-var1-which-var1-is-derived-from) – Theo Sep 25 '20 at 09:05

0 Answers0