在PowerShell SELECT中解析JSON

Joc*_*ick 2 powershell json azure-powershell

我正在尝试使用powershell命令列出所有Azure VM的大小.问题是该HardwareProfile属性返回一个JSON对象,我想解析它并只使用vmSize该对象的属性值.

所以我正在运行这个命令:

Get-AzureRmVM
Run Code Online (Sandbox Code Playgroud)

这给了我这个:

ResourceGroupName        : TESTRG
...
Name                     : ubuntu-server
...
HardwareProfile          : {
                             "vmSize": "Standard_DS2"
                           }
...
Run Code Online (Sandbox Code Playgroud)

注意HarwareProfile值中的JSON .

我想做的是:

Get-AzureRmVM | Select ResourceGroupName, Name, HardwareProfileText `
              | Out-Gridview -PassThru
Run Code Online (Sandbox Code Playgroud)

哪个有效 - 只是,我想摆脱HardwareProfileText中的JSON表示法.使用Format-Table看起来像这样:

ResourceGroupName Name          HardwareProfileText
----------------- ----          -------------------
TESTRG            ubuntu-server {...
Run Code Online (Sandbox Code Playgroud)

所以问题是:我怎样才能获得vmSize此表中的值?我可以潜入ConvertFrom-Json某个地方吗?

Har*_* F. 5

你不能直接使用select-expression并将json-string转换为对象吗?所以你可以在以后的管道中使用它.

就像是 :

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

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

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

这将为您提供仅具有VmSize的属性.您可以将表达式select与普通属性或多个表达式组合,然后如果要过滤其他条件,则继续将其传递给管道.