我一直在打破这个问题一段时间。我运行两个管道来生成两个元组数组。每个元组都包含(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',
}
]
如何组合这些管道以产生所需的输出?或者我是否比必要时更复杂?
答案 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