如何从powershell脚本中的列表中查询

时间:2018-04-30 16:25:43

标签: powershell

我有json格式的回复:

$|

我在PowerShell脚本中尝试做的是查明nodes_table中是否有可用的节点并获取其状态。例如:

{
    "properties": {
        "basic": {
            "nodes_table": [
                {
                    "node": "node1.prod.local:80",
                    "state": "active",
                    "weight": 1
                },
                {
                    "node": "node2.prod.local:80",
                    "state": "disabled",
                    "weight": 1
                },
                {
                    "node": "node3.prod.local:80",
                    "state": "disabled",
                    "weight": 1
                },
                {
                    "node": "node4.prod.local:80",
                    "state": "disabled",
                    "weight": 1
                },
                {
                    "node": "node5.prod.local:80",
                    "state": "active",
                    "weight": 1
                }
            ]
        }
    }
}

问题: 我在获取“特定”节点的状态时遇到问题,所以我想检查“给定”节点是否在表中,并且该节点的状态是活动/禁用的。我将如何在脚本中实现这一目标?

2 个答案:

答案 0 :(得分:4)

$Active = $GetNodesResponse.properties.basic.nodes_table |
            Where {$_.Node -eq "node1.prod.local:80" -and $_.state -eq "active"}
If ($Active) {Write-Output  "Node matches and is Active"}

答案 1 :(得分:1)

要检查多个字符串,请使用Where {$_.Node -in "node1.prod.local:80", "node5.prod.local:80" -and $_.state -eq "active"} 运算符

-like

或者您可以使用-matchWhere {$_.Node -like "node[15].prod.local:80" -and $_.state -eq "active"} 运算符来匹配模式,如下所示:

{{1}}