【powershell】Selectを利用して特定の項目だけを表示させる

Powershell Powershell

PowershellでJSON形式のオブジェクトから Select を利用して特定の項目だけを表示することを試してみました。

広告

Select を利用して特定の項目だけを表示させる

今回は以下のjson形式で書かれた内容から名前(name)と id の一覧だけを表示させてます。

・hogehoge.txt

{
  "title": "hogehoge",
  "values": [
    {
      "name": "hoge01",
      "id": "001",
      "properties": {
        "Number": "0001",
        "animal": [
          "cat",
          "monkey",
          "elephant"
        ],
        "location": [
          "Australia",
          "Japan",
          "China"
        ]
      }
    },
    {
      "name": "hoge02",
      "id": "002",
      "properties": {
        "Number": "0002",
        "animal": [
          "cat02",
          "monkey02",
          "elephant02"
        ],
        "location": [
          "Australia",
          "Japan",
          "China"
        ]
      }
    },
    {
      "name": "hoge03",
      "id": "003",
      "properties": {
        "Number": "0003",
        "animal": [
          "cat03",
          "monkey03",
          "elephant03"
        ],
        "location": [
          "Australia",
          "Japan",
          "China"
        ]
      }
    }
  ]
}
広告

コマンドと実行結果

以下のコマンドで name と id のみを表示することが可能です。

#上記のファイルの読み込み
$content_json = get-content C:\hogehoge\hogehoge.txt | ConvertFrom-json

#nameとidのみを表示
$content_json.values | Select "name","id"

・実行結果

PS C:\> $content_json.values | Select "name","id"

name   id
----   --
hoge01 001
hoge02 002
hoge03 003


PS C:\>

[参考] animal と location を表示させる

上記の内容の中から今度は animal と location を表示させてみます。
その場合には以下のようにコマンドを実行します。

PS C:\> $content_json.values.properties | Select "animal","location"

animal                        location
------                        --------
{cat, monkey, elephant}       {Australia, Japan, China}
{cat02, monkey02, elephant02} {Australia, Japan, China}
{cat03, monkey03, elephant03} {Australia, Japan, China}


PS C:\>

animal と location には複数の値が格納されているのでリスト形式で表示されます。

コメント

タイトルとURLをコピーしました