从多个管道构造JSON对象

时间:2016-06-13 22:37:30

标签: json powershell

我一直在打破这个问题一段时间。我运行两个管道来生成两个元组数组。每个元组都包含(filename, property)

# create pipeline of (file, property1) tuples
$prop1 = Get-ChildItem *.prop1 -PipelineVariable fi |
           Get-Content -Tail 150 |
           Select-String -Pattern "  Pattern1 (\d+)" | 
           ForEach-Object { $_.Matches } |
           ForEach-Object { [System.Tuple]::Create($fi.Name, $_.Groups[1].Value) }

# create pipeline of (file, property2) tuples
$prop2 = Get-ChildItem *.prop2 -PipelineVariable fi | 
           Get-Content -Tail 5 | 
           Select-String -Pattern "  Pattern2 (\d+)" | % { $_.Matches } |
           ForEach-Object { $_.Matches } | 
           ForEach-Object { [System.Tuple]::Create($fi.Name, $_.Groups[1].Value) }

$result = ????
ConvertTo-Json $result

现在我想在filename上组合这些元组管道来生成JSON输出,如:

[
  {
     'file':'filename1',
     'prop1':'value1',
     'prop2':'value2',
  },
  {
     'file':'filename2',
     'prop1':'value3',
     'prop2':'value3',
  }
]

如何组合这些管道以产生所需的输出?或者我是否比必要时更复杂?

1 个答案:

答案 0 :(得分:2)

不使用Tuple将属性值绑定到文件名,而是使用Hashtable,其中文件名是键:

$FileProps = @{}
Get-ChildItem *.prop1 -PipelineVariable fi |
           Get-Content -Tail 150 |
           Select-String -Pattern "  Pattern1 (\d+)" | 
           ForEach-Object { $_.Matches } |
           ForEach-Object { $FileProps[$fi.BaseName] = @{ 'filename' = $fi.BaseName; 'prop1' = $_.Groups[1].Value }}

Get-ChildItem *.prop2 -PipelineVariable fi | 
           Get-Content -Tail 5 | 
           Select-String -Pattern "  Pattern2 (\d+)" | % { $_.Matches } |
           ForEach-Object { $_.Matches } | 
           ForEach-Object { $FileProps[$fi.BaseName]['prop2'] = $_.Groups[1].Value }

现在根据哈希表条目创建一堆自定义对象,并将它们转换为json:

$Json = $FileProps.Keys |ForEach-Object {
    New-Object psobject -Property $FileProps[$_]
} |ConvertTo-Json