无法从JSON数据中获取单个详细信息

时间:2018-08-07 09:11:52

标签: powershell pester

"Ns": {
    "value": [
        {
            "Nname": "exa",
            "SR": [
                {
                    "name": "port1",
                    "properties": {
                        "description": "Allow port1",
                        "destinationPortRange": "1111",
                        "priority": 100
                    }
                },
                {
                    "name": "port1_0",
                    "properties": {
                        "description": "Allow port1",
                        "destinationPortRange": "1111",
                        "priority": 150
                    }
                },
                {
                    "name": "port2",
                    "properties": {
                        "description": "Allow  1115",
                        "destinationPortRange": "1115",
                        "priority": 100,
                    }
                }
            ]
        }
    ]
}

想断言优先级和名称的详细信息,但无法做到。

这是我所实施的:

$Ndetails = templateProperties.parameters.Ns.value.SR
foreach ($Ndata in $Ndetails) {
    $Ndata .properties.destinationPortRange |
        Should -BeExactly @('1111','1111','1115')
} 

如何在PowerShell中使用Pester解决相同的问题?

1 个答案:

答案 0 :(得分:3)

您无需为此使用foreach。您可以为此使用Select-Object。假设您的JSON与注释中的@Mark Wragg链接:

$Json = @'
[{
    "Ns": {
        "value": [{
            "Nname": "exa",
            "SR": [{
                    "name": "port1",
                    "properties": {
                        "description": "Allow port1",
                        "destinationPortRange": "1111",
                        "priority": 100
                    }
                },
                {
                    "name": "port1_0",
                    "properties": {
                        "description": "Allow port1",
                        "destinationPortRange": "1111",
                        "priority": 150
                    }
                },
                {
                    "name": "port2",
                    "properties": {
                        "description": "Allow  1115",
                        "destinationPortRange": "1115",
                        "priority": 100
                    }
                }
            ]
        }]
    }
}]
'@

$t = $Json | ConvertFrom-Json

您的测试文件应如下所示:

$result = $t.Ns.value.SR.properties.destinationPortRange
it 'destinationPortRange matches' {
  $result | Should -BeExactly @('1111','1111','1115')
}

说明

您对foreach的使用不正确,因为您比较了单个元素(还要注意,我删除了不必要的空间)

$Ndata.properties.destinationPortRange

到数组

| Should -BeExactly @('1111','1111','1115')

您要做的是像我的示例中那样,将数组与数组进行比较。