【愚痴】標準のpowershellではYAMLを扱えないことを知らなかった!XMLとJSONは扱えるのに・・・
PowershellはXMLを扱える
[System.Xml.XmlDocument]型にすれば扱えるようだ。
# # read XML file # function MyReadXML { [CmdletBinding()] param( [Parameter(Mandatory=$True, ValueFromPipeline=$True)] [ValidateNotNullOrEmpty()] [string[]]$File ) begin { } process { $doc = [System.Xml.XmlDocument](Get-Content -Encoding UTF8 -Raw $File ) $x = $doc.root.StartPoint.X $y = $doc.root.StartPoint.Y $u = $doc.root.Pixel.Unit $property = @{ X = $x Y = $y Unit = $u } $output = New-Object -TypeName PSObject -Property $property Write-Output $output } end { } }
以下のようなXMLデータに対して
PS >cat .\p001.xml <root> <StartPoint> <X>-0.17839816</X> <Y>0.652558</Y> </StartPoint> <Pixel> <Unit>7.15727999999993E-06</Unit> <Width>800</Width> <Height>500</Height> <Iteration>300</Iteration> </Pixel> </root>
上記の関数で読み込ませると、Custom Objectで返してくれる(ようだ)。
PS >get-childitem *.xml | MyReadXML Y Unit X - ---- - 0.652558 7.15727999999993E-06 -0.17839816 0.6500171656 1.71774720000006E-06 -0.17577143824 0.6498299311552 6.63050419200228E-07 -0.1755172116544
JSONも扱える
XMLのときとはデータの構造を変えてしまっているが、convertfrom-jsonでPSCustomObjectで返してくれる(ようだ)。
PS >cat .\ex1.json { "startpoint": { "x":-0.17839816, "y":0.652558 }, "pixel": { "unit":7.15727999999993E-06, "width":800, "height":500 }, "iteration":300 }
PS >$co = ( get-content .\ex1.json | convertfrom-json ) PS >$co startpoint pixel iteration ---------- ----- --------- @{x=-0.17839816; y=0.652558} @{unit=7.15727999999993E-06; width=800; height=500} 300 PS >$co.gettype() IsPublic IsSerial Name BaseType -------- -------- ---- -------- True False PSCustomObject System.Object PS >$co.startpoint.x -0.17839816 PS >
YAMLは標準では扱えないみたいだ
ちょっと、標準でないモジュールを使うのは腰が引けるし、現在使用しているWindows PowerShellのバージョンは5.1でクロスプラットフォームのpowershellに移行する度胸はなかった。以前、クロスプラットフォームのpwshをインストールして痛い目に会っているので、powershell自体をバージョンアップするのは私には危険すぎる。
やめておこう。
PS >$psversiontable Name Value ---- ----- PSVersion 5.1.19041.1682 PSEdition Desktop PSCompatibleVersions {1.0, 2.0, 3.0, 4.0...} BuildVersion 10.0.19041.1682 CLRVersion 4.0.30319.42000 WSManStackVersion 3.0 PSRemotingProtocolVersion 2.3 SerializationVersion 1.1.0.1
了