LoginSignup
11
7

More than 5 years have passed since last update.

PowershellでYAMLを扱う(Import-YAML)

Last updated at Posted at 2016-09-04

世間では YAML なるファイルフォーマットがナウいと聞いたので、素の Windows でも使えるように Powershell で使えるパーサを作ってみました。いつものように JScript でも良かったのですが、Powershell の勉強がてら。。。

いまいち powershell のモジュールの使い方が分かっていないのですが、とりあえず動くようになったので github に公開しました。
色々足りない部分(後述)があるので実装状況としては 50% も無いと思われます。

使用感は以下のような感じです。

PS D:\dev\Import-YAML> Import-Module .\Import-YAML.psm1 -verbose
詳細: パス 'D:\dev\Import-YAML\Import-YAML.psm1' からモジュールを読み込んでいます。
詳細: 関数 'Import-YAML' をインポートしています。
PS D:\dev\Import-YAML>
PS D:\dev\Import-YAML>
PS D:\dev\Import-YAML> cat .\test.yml
number: 123
string: C:\temp\hoge\fuga
boolean:  yes
boolean2: on
boolean3: true
array:
  - 1
  - 2
  - 3
# comment
flowstyle:
  {
    str: "hoge",
    num: 123,
    ary: [true, false, null]
  }
PS D:\dev\Import-YAML>
PS D:\dev\Import-YAML>
PS D:\dev\Import-YAML>
PS D:\dev\Import-YAML> $YAML = Import-YAML .\test.yml
PS D:\dev\Import-YAML> $YAML

Name                           Value
----                           -----
array                          {1, 2, 3}
number                         123
flowstyle                      {ary, str, num}
boolean2                       True
boolean3                       True
boolean                        True
string                         C:\temp\hoge\fuga


PS D:\dev\Import-YAML>

JSON に比べると Windows のファイルパスがそのまま書けるので、「読みやすく、書きやすい」というのも納得できます。
あとコメントが埋め込めるのも良いと思います。

YAML のデータは以下の形式でインポートされます。以下の形式以外は未対応です。

YAML Powershell(.NET)
string System.String
decimal System.Double
boolean System.Boolean
datetime System.Datetime
null null(?)
Sequence System.Collections.ArrayList
Mapping System.Collections.HashTable

何となく見ての通りですが、できることは以下の通り

  • 正の整数、文字列、真偽値、日付型、null、シーケンス、マッピングの解釈
  • ネストしたシーケンス、マッピングの解釈
  • ブロックスタイルとフロースタイルの解釈
  • コメントの解釈(無視)
  • etc.

逆に未対応は以下の通り

  • 読みやすい形での構文エラーの通知
  • decimal型各種データ型の解釈及び型宣言
  • ブロックスタイル文字列の解釈
  • アンカーとエイリアスの解釈
  • etc.

まだヘルプもユーティリティも無いですが、テキストファイル1枚だけなので試運転程度であれば。
構文が平易で非エンジニアにも優しい感じなので、業務利用も視野に入れて作り込みたいところ。

参考資料

PowerShell のモジュール詳解とモジュールへのコマンドレット配置手法を考える - tech.guitarrapc.cóm
Rubyist Magazine - プログラマーのための YAML 入門 (初級編)

11
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
7