通过 invoke-webrequest 从 http 响应触发器中读取 json 值



我正在尝试从 invoke-web 请求的 JSON 响应中获取特定值。但价值不是捕获 已尝试使用以下脚本,其中$body包含响应。

$url = "http://localhost:9096/getMachineStatus"
$HTTP_Request = [System.Net.WebRequest]::Create($url)
$HTTP_Response = $HTTP_Request.GetResponse()
$HTTP_Status = [int]$HTTP_Response.StatusCode
$body = Invoke-WebRequest -Uri $url 

上述脚本的响应:

{
"Name": "LocalTestMachine",
"Profile": "QA",
"Stacks": [
{
"Region": "Mumbai-1",
"State": "Stopped",
"StackName": "QA",
"StackCreationStatus": "CREATE_Success",
"Instances": [
{
"MachineName": "LocalMachine",
"IpAddress": "10.10.10.164",
"State": "stopped",
"InstanceId": "i-0777e90151b22da44",
"ImageId": "ami-0322ff2d8d099g56c",
"CustomImageName": "ubuntu-trusty-16.04",
"InstanceType": "m4.large",
"LaunchTime": "2019-09-04T02:42:36-04:00",
"AvailabilityZone": "Mumbai-1",
"Tags": [
{
"Key": "ProductLine",
"Value": "Cloud"
}]
}]
}]
}

我只想检索与对象State关联的值,该值Stopped.

我试过
$currentVMState = $body | where {$_.State}它不起作用

若要获取Stacks数组中第一个State项的值,请执行以下操作:

$json = $body | ConvertFrom-Json
$json.Stacks[0].State

返回

停止

首先,您需要将响应转换为 json:

$json = $body | ConvertFrom-Json

然后迭代$json对象以获取状态值:

$json.stacks.instances | ForEach-Object { $_.State }

最新更新