json ファイルから PSObject を作成しています
bar.json
{
"derp": {
"buzz": 42
},
"woot": {
"toot": 9000
}
}
ConvertFrom-Json を使用して JSON から PSCustomObject を作成できます
$foo = Get-Content .\bar.json -Raw |ConvertFrom-Json
$foo.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
ただし、複数のjsonファイルをスプラットしようとすると、配列が得られます
$foo = Get-Content .\*.json -Raw |ConvertFrom-Json
$foo.gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False Object[] System.Array
$foo を反復するには、オブジェクトの種類に応じて 2 つの異なるコード パスが必要です。
複数の json ファイルから単一のオブジェクトを取得できますか?
そうでない場合、オブジェクトの配列を単一のオブジェクトに圧縮するにはどうすればよいですか?
$bar
のすべての配列項目を含む新しいオブジェクトを作成しようとしました$foo
$bar = new-object psobject
$bar | add-member -name $foo[0].psobject.properties.name -value $foo[0].'derp' -memberType NoteProperty
Walter Mitty の要求に従って更新します。単一のファイルをロードして実行すると$foo[0]
$foo = Get-Content .\bar.json -Raw |ConvertFrom-Json
$foo[0].gettype()
IsPublic IsSerial Name BaseType
-------- -------- ---- --------
True False PSCustomObject System.Object
$foo[0]
derp woot
------------ ------------
@{Provisioners=System.Object[]; OS=windows; Size=; V... @{Provisioners=System.Object[]; OS=windows; Size=; V...
解決
最初に AP の回答を実装しましたが、後で mklement0 の回答を使用するようにリファクタリングしました。
$allObjects は配列ですが、探していた名前で値を参照できます
$allObjects = @(
Get-ChildItem '.\foo' -Filter *.json -Recurse | Get-Content -Raw | ConvertFrom-Json
)
# iterating over nested objects inside an array is hard.
# make it easier by moving all array objects into 1 parent object where
# the 'key' is the name (opposed to AP's answer where filename = key)
$newObject = New-Object PSObject
foreach ($i in $allObjects) {
$i.psobject.members | ?{$_.Membertype -eq 'noteproperty'} |%{$newObject | add-member $_.Name $_.Value}
}