Welcome Forums General PowerShell Q&A Best way to add JSON object to another

Viewing 2 reply threads
  • Author
    Posts
    • #62485
      Participant
      Topics: 16
      Replies: 50
      Points: 58
      Rank: Member

      I’m struggling with the right way to add an object retrieved from json to a custom object.

      What I want to be able to do is add this custom object and set the value for Enabled to $true in some instances and other instances set it to $false. I need to replicate this task many times and then repost it with the values I want in the task sequence I need. (This is for TFS 2015 r3 release tasks.)
      The issue is when I have the same object $tasks2add[0] added more than once in my new object and I change the value of enabled to either true or false it resets all the previous ones I added to my custom object to the same value.

      I’ve tried using several differnt methods of adding and I cannot seem to find the on that doesn’t seem to make a reference to the value rather than an explicitly copying the object from the json source.

      My sample code is in this gist:

      https://gist.github.com/crshnbrn66/f9779247e5b3dc8709aa2f72b51095aa

    • #62490
      Participant
      Topics: 0
      Replies: 10
      Points: 0
      Rank: Member

      Hello! You should copy your object with all its properties, not just referencing the properties.
      Replace these lines:

      $newArraylist.Add((New-object pscustomobject ($tasks2add[0])))
      $newArraylist.Add((New-object pscustomobject ($tasks2add[1])))
      $newArraylist.Add((New-object pscustomobject ($tasks2add[0])))
      $newArraylist.Add((New-object pscustomobject ($tasks2add[1])))

      With these:

      $newArraylist.Add($tasks2add[0].PSObject.Copy())
      $newArraylist.Add($tasks2add[1].PSObject.Copy())
      $newArraylist.Add($tasks2add[0].PSObject.Copy())
      $newArraylist.Add($tasks2add[1].PSObject.Copy())

      And voilĂ ! It works.

    • #62556
      Participant
      Topics: 16
      Replies: 50
      Points: 58
      Rank: Member

      Thank you Nimms Great Tip thank you very much… Much Appreciated.

Viewing 2 reply threads
  • The topic ‘Best way to add JSON object to another’ is closed to new replies.