Best way to add JSON object to another

Tagged: 

This topic contains 2 replies, has 2 voices, and was last updated by Profile photo of Thom Schumacher Thom Schumacher 2 months ago.

  • Author
    Posts
  • #62485
    Profile photo of Thom Schumacher
    Thom Schumacher
    Participant

    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:

  • #62490
    Profile photo of nimms
    nimms
    Participant

    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
    Profile photo of Thom Schumacher
    Thom Schumacher
    Participant

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

You must be logged in to reply to this topic.