从条件中调用值提取变量-获取错误消息

时间:2019-06-25 04:21:19

标签: json powershell vnet convertto-json

我正在尝试进行验证。用给定值检查部署的值。我使用RestAPI方法从Azure资源提取vnet值,并从Object转换为json,因为vnet对象给了我空对象(@ {value = System.Object []})。以下是我得到的Json代码:

{
  "value": [
    {
      "properties": "@{virtualNetworkSubnetId=/subscriptions/<XXXX>/resourceGroups/<XXXX>/providers/Microsoft.Network/virtualNetworks/<XXXX>/subnets/<XXXX>; ignoreMissingVnetServiceEndpoint=True; state=Ready}",
      "id": "/subscriptions/<XXXX>/resourceGroups/<XXXX>/providers/Microsoft.DBforPostgreSQL/servers/<XXXX>/virtualNetworkRules/<XXXX>",
      "name": "<XXXX>",
      "type": "Microsoft.DBforPostgreSQL/servers/virtualNetworkRules"
    }
  ]
}

下面的powershell命令是比较该值,但会收到一条错误消息:$ vnet.name和$ vnet.id为$ null

$vnet= ( $vnet | ConvertTo-Json)

   It "has this number of vNet Rules defined: $($config.vnetRules.count)" 
  {
    $vnet.count | Should -Be $config.vnetRules.count    
   }

   #$vnet.count is working and giving an success message

   foreach ($vnetRule in $config.vNetRules) {

    Write-Host $vnet            #-> getting Json 
    Write-Host $vnet.Name       #-> return as Empty($null)
        Write-Host $vnet.value.Name #-> return as Empty($null)
    Write-Host $vnet.id         #-> return as Empty($null)
        Write-Host $vnet.value.id   #-> return as Empty($null)

    it "has a vNet rule named: $($vnetRule.ruleName)" {
        $vnet.name | Should -Be $vnetRule.ruleName
    }

    it "has a vNet Rule Subnet ID of: $($vNetRule.subnetId)" {
        $vnet.value.id | Should -Be $vNetRule.subnetId
    }

}

返回$ null。

1 个答案:

答案 0 :(得分:0)

在尝试重新创建invoke-restmethod输出时,我使用JSON数据包作为输入来创建$vnet变量。

我相信问题是您正在使用Write-host来显示对象而不是简单地显示对象名称。 Write-host将尝试将复杂对象转换为字符串,因此您将看到奇怪的输出,如下所示。当我简单地拿出对象时,会看到区别吗?

enter image description here

现在,$vnet具有4个属性id, name, properties, type,可以如图所示调用。 在这种情况下,您已将变量$vnet转换为json,然后尝试显示其属性。但是Jsonlength外没有任何属性。因此,调用这些属性将为您提供null。

enter image description here