代码之家  ›  专栏  ›  技术社区  ›  Vinay

从Powershell读取JSON

  •  1
  • Vinay  · 技术社区  · 7 年前

    我正在尝试读取存储在VM notes中的JSON数据。下面是我执行的获取VM注释的命令

    Get-VM testbox |format-list Notes
    

    输出为

    Notes : {
                "Program":  "AAA",
                "Project":  "BBBB"
            }
    

    我想把程序的值读入一个变量。我该怎么做?

    3 回复  |  直到 7 年前
        1
  •  3
  •   Frode F.    7 年前

    使用 ConvertFrom-JSON 要在 notes -属性。我会将转换后的笔记存储在一个变量中,以防您需要访问 Project 或稍后json的另一部分。尝试:

    $vm = Get-VM testbox
    $notes = $vm.Notes | ConvertFrom-JSON
    $mynewvar = $notes.program
    
        2
  •  0
  •   Dave    7 年前

    您的json无效,如果是,则可以:

     (Get-VM -VMName TestBox).notes | ConvertFrom-Json
    

    有效Json:

    {
        "Notes":
        {
            "Program":  "AAA",
            "Project":  "BBBB"
        }
    }
    
        3
  •  -1
  •   Jcl    7 年前

    完全未经测试(目前无法测试),但类似于:

    Get-VM testbox | Select-Object -ExpandProperty Notes | ConvertFrom-Json
    

    Documentation for ConvertFrom-Json here