【PowerShell】Selectコマンドで特定の項目だけを取り出す

Powershell Powershell
この記事は約5分で読めます。

PowershellでJSON形式のオブジェクトから Select コマンドを利用して特定の項目だけを取り出すことを試してみました。

広告

1.やりたいこと

今回は以下のjson形式で書かれたテキストファイルから名前(name)と id の一覧の情報のみを取り出します。

{
  "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
---- --
hoge01 001
hoge02 002
hoge03 003

2.Selectコマンドで特定の項目だけを取り出す

以下のPowershellコマンドで 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をコピーしました