在 PowerShell SELECT 中解析 JSON

Parse JSON in PowerShell SELECT

我正在尝试使用 powershell 命令列出我的所有 Azure VM 及其大小。 问题是 HardwareProfile 属性 returns 一个 JSON 对象,我只想解析和使用它的 vmSize 属性 值对象。

所以我运行这个命令:

Get-AzureRmVM

这给了我这个:

ResourceGroupName        : TESTRG
...
Name                     : ubuntu-server
...
HardwareProfile          : {
                             "vmSize": "Standard_DS2"
                           }
...

注意 HarwareProfile 值中的 JSON。

我想做的是:

Get-AzureRmVM | Select ResourceGroupName, Name, HardwareProfileText `
              | Out-Gridview -PassThru

有效 - 只是,我想去掉 HardwareProfileText 中的 JSON 符号。使用 Format-Table 看起来像这样:

ResourceGroupName Name          HardwareProfileText
----------------- ----          -------------------
TESTRG            ubuntu-server {...

所以问题是:我怎样才能在这个 table 中只得到 vmSize 的值?我可以偷偷 ConvertFrom-Json 到什么地方吗?

我不知道 get-azureRmVm 函数,但它与 属性 InstanceSize 而不是 HardwareProfileText 一起工作得很好。

Import-Module 'Azure'
Get-AzureVM | Select ResourceGroupName, Name, InstanceSize `
          | Out-Gridview -PassThru

Result

不能直接用select表达式,把json字符串转成对象吗?因此您可以稍后在您的管道中使用它。

类似于:

select @{Name="VMSize";Expression={($_|ConvertFrom-Json).vmSize}};

给定你的 json 作为文件中的文本(用于简单测试):

(Get-Content -raw C:\tmp\test.json)|select @{Name="VMSize";Expression={($_|ConvertFrom-Json).vmSize}};

这会给你一个只有 VmSize 的 属性。您也可以将表达式 select 与普通属性或多个表达式组合在一起,然后继续将其传递到管道中(如果您希望根据其他条件进行过滤)。