我有一个脚本将显示主机中的所有虚拟机,由于此结果是 RESTful API (JSON) 的输出,因此结果是嵌套的。
$Json 变量的输出 -
{
"ErrorAdditionalDetails": null,
"ErrorCode": null,
"ErrorMessage": null,
"Success": true,
"VirtualMachines": [
{
"VirtualMachineName": "xxxxxxxxxxx"
}
]
}
$json | Select-Object VirtualMachineName
上面的命令显示空白。
结果应该是:
VirtualMachineName : xxxxxxxxxxx
JSON 是(结构化)文本,因此为了在其上使用 OO 技术,您必须首先将其解析为 对象图,这就是
ConvertFrom-Json
的作用。
然后您可以简单地使用点符号(属性访问)来访问感兴趣的属性:
($json | ConvertFrom-Json).VirtualMachines
这将输出
[pscustomobject] @{ VirtualMachineName = "xxxxxxxxxxx" }
的等价物,即一个 [pscustomobject]
实例,其 .VirtualMachineName
属性包含感兴趣的值。
要仅输出属性 value (
"xxxxxxxxxxx"
),只需将 .VirtualMachineName
附加到上面的命令即可。
注:
顶级
.VirtualMachines
属性是一个 数组。
PowerShell 的成员访问枚举的工作方式是,如果数组仅包含一个元素,您将获得该元素本身作为输出;具有两个或更多元素,您将获得一个由[object[]]
/字符串组成的
数组(
[pscustomobject]
)。