【问题标题】:Powershell variable not displaying nested objectPowershell变量不显示嵌套对象
【发布时间】:2019-12-24 14:32:07
【问题描述】:

我正在发送一个返回对象的 GET 请求。使用邮递员,我得到:

{
"changedInstance": {
    "change": "Created",
    "instanceAfterChange": {
        "instanceId": "123",
        "schemaName": "RBAC",
        "className": "PermissionCategory",
        "properties": {
            "Name": "IModel Schema Management Service",
            "TypeId": 2,
            "TypeName": "Service Access and Permissions"
        }
    }
}}

但是当我通过 Powershell 发送请求时,我得到了响应:

@{change=Created; instanceAfterChange=}

我提出的要求:

$Response = Invoke-RestMethod -Uri $base_url/v2.4/Repositories/BentleyCONNECT--Main/RBAC/PermissionCategory -Method Post -Headers @{'Authorization' = 'Bearer ' + $global:token} -Body $postParams -ContentType "application/json"

我已经检查了所有的标题值和正文,没有丢失任何值。

“instanceAfterChange”属性为空,但是当我在 fiddler 中监视相同的请求时,它会显示正确的响应。我的问题是,为什么 Powershell 将其显示为空,即使它不是。

【问题讨论】:

    标签: powershell


    【解决方案1】:

    ConvertFrom-Json 从您的 JSON 输入构造一个 [pscustomobject] 实例,您看到的 (@{change=Created; instanceAfterChange=}) 是该实例的 .changedInstance 属性值的默认显示格式。

    由于 PowerShell 7.0 的错误,默认显示格式使其显示好像属性 instanceAfterChange 为空,但实际上不是。

    • 具体来说,错误是在[pscustomobject] 实例上调用.ToString() 会意外产生空字符串 - 请参阅this GitHub issue。

    • 哈希表-like 显示[pscustomobject]s 作为属性值的表示形式-如您的问题所示并在this answer中解释-涉及@987654331 @ 调用 嵌套 [pscustomobject] 实例,这就是错误出现的原因。

    因此,访问嵌套的 [pscustomobject]s 属性应该没有问题,例如,$convertedFromJson.changedInstance.instanceAfterChange.schemaName 应该产生 RBAC。

    验证数据是否存在的简单方法是转换回 JSON (ConvertTo-Json) 或通过 Format-Custom 可视化结构。

    一个简化的例子:

    $convertedFromJson = '{
      "changedInstance": {
        "instanceAfterChange": {
          "instanceId": "123",
          "schemaName": "RBAC"
        }
      }
    }
    ' | ConvertFrom-Json
    
    # Output as-is: the bug makes .changedInstance appear empty.
    $convertedFromJson
    
    '---'
    
    # Access a nested property - this works.
    $convertedFromJson.changedInstance.instanceAfterChange.schemaName
    
    '---'
    
    # Visualize the structure of the nested object.
    $convertedFromJson | Format-Custom
    

    以上产出:

    changedInstance
    ---------------
    @{instanceAfterChange=}  # DISPLAY BUG: .instanceAfterChange appears empty.
    ---
    RBAC # OK: accessing a property of .instanceAfterChange works.
    ---
    
    # Visualization of the nested object's structure via Format-Custom
    class PSCustomObject
    {
      changedInstance = 
        class PSCustomObject
        {
          instanceAfterChange = 
            class PSCustomObject
            {
              instanceId = 123
              schemaName = RBAC
            }
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 2013-01-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多