如何在PowerShell脚本中查询指定JSON响应的节点列表
Got it, let's walk through how to check your node states using PowerShell with that JSON data you have. Here's a practical, reusable approach:
Parsing the JSON Data
First, you need to convert your JSON response into a PowerShell object—this makes it trivial to access and filter the node list. If your JSON is stored as a string (or coming from an API/file), here's how to parse it:
# Replace this with your actual JSON input (could also load from a file via Get-Content) $jsonInput = @" { "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 } ] } } } "@ # Convert JSON to a structured PowerShell object $nodeTable = ($jsonInput | ConvertFrom-Json).properties.basic.nodes_table
Creating a Reusable Function
Next, make a simple function to query any node's state. This keeps your code clean and lets you reuse the logic easily:
function Get-TargetNodeState { param( [Parameter(Mandatory=$true, HelpMessage="The node to check (e.g., node1.prod.local:80)")] [string]$NodeName, [Parameter(Mandatory=$true, HelpMessage="The parsed node table from your JSON")] [array]$NodeList ) # Find the matching node entry $matchingNode = $NodeList | Where-Object { $_.node -eq $NodeName } if ($matchingNode) { Write-Output "Node *$NodeName* is currently **$($matchingNode.state)**" } else { Write-Warning "⚠️ Node '$NodeName' was not found in the node list" } }
Example Usage
Now you can call the function to check any node's status:
# Check an active node Get-TargetNodeState -NodeName "node1.prod.local:80" -NodeList $nodeTable # Check a disabled node Get-TargetNodeState -NodeName "node2.prod.local:80" -NodeList $nodeTable # Test a node that doesn't exist Get-TargetNodeState -NodeName "node6.prod.local:80" -NodeList $nodeTable
Quick Notes:
- The
ConvertFrom-Jsoncmdlet turns your raw JSON into a PowerShell object, so you can drill down to thenodes_tableproperty easily. - The function filters the node list to find your target, then returns a clear message with the state (bolded for visibility) or a warning if the node isn't present.
- You can adapt this to pull JSON directly from an API by replacing the hardcoded
$jsonInputwith aInvoke-RestMethodcall, if needed.
内容的提问来源于stack exchange,提问作者Shahboz
相关产品推荐
相关产品推荐

