【问题标题】:Powershell Append PSCustomObject to nested PSCustomObjectPowershell 将 PSCustomObject 附加到嵌套的 PSCustomObject
【发布时间】:2021-04-26 21:08:57
【问题描述】:

我的问题是我有一个远程 API,它为我提供了一个具有 10 级深度嵌套的 JSON,我需要向其中一个添加另一个数组/哈希表/PSCustomObject(无论您想调用什么)。

JSON 看起来像这样:

{  
  "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"
                }  
              ]  
            }  
          }  
        ]  
      }  
    ]  
  ]  
}  

返回对象是一个哈希表,但是当我尝试访问点表示法中的值时,它变成了 PSCustomObject:

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

它不允许我使用其他符号:

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

真正棘手的部分(对我而言)是将一个新的 hastable 附加到“静态”哈希表中,以使哈希表的其余部分保持不变。

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

我本来会使用 PHP 或 Python,但对于这个项目,我必须使用 Powershell,而且我遇到了各种 PS 行为与我预期不同的事情。

非常感谢任何帮助!

【问题讨论】:

    标签: powershell hashtable pscustomobject


    【解决方案1】:

    static 是一个数组,你可以往里面添加新的元素:

    $newStaticRoute = [pscustomobject]@{
      destination = '192.168.0.0'
      netmask = '255.255.0.0'
    }
    
    $result.result.modules.data.segments.routes.static += $newStaticRoute
    

    【讨论】:

      猜你喜欢
      • 2021-04-04
      • 1970-01-01
      • 1970-01-01
      • 2020-08-25
      • 2021-12-06
      • 1970-01-01
      • 2016-06-23
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多