Powershell Append PSCustomObject to nested PSCustomObject

396 Views Asked by At

My problem is that I have a remote API giving me a JSON with 10 levels deep nesting and I need to add another array/hashtable/PSCustomObject (whatever you want to call it) to one of them.

The JSON looks like this:

{  
  "result": [  
    "modules": [  
      "data": {  
        "segments": [  
          {  
            "routes": {  
              "static": [  
                {  
                  "destination": "10.0.0.0",
                  "netmask": "255.0.0.0"
                },
                {  
                  "destination": "172.16.0.0",
                  "netmask": "255.240.0.0"
                }  
              ]  
            }  
          }  
        ]  
      }  
    ]  
  ]  
}  

The return object is a Hashtable, however when I try to access the values in dot notation, it turns into PSCustomObject:

$statics = $result.result.modules.data.segments.routes.static

It won't let me use the other notation:

$statics = $result['result']['modules']['data']['segments']['routes']['static']
Error: Cannot index into a null array

The real tricky part (for me) is to to append a new hastable to the "static" hashtable in such a way that the rest of the hashtable remains intact.

$newroute = @{
    destination = "1.1.1.1."
    netmask = "255.255.255.255"
}

I would have used PHP or Python but for this project I must use Powershell and I'm running into all sorts of things where PS behaves different from what I expect.

Any help is greatly appreciated!

1

There are 1 best solutions below

0
On

static is an array, you can add new items to it:

$newStaticRoute = [pscustomobject]@{
  destination = '192.168.0.0'
  netmask = '255.255.0.0'
}

$result.result.modules.data.segments.routes.static += $newStaticRoute