Powershell:从 txt 中提取几个字符串并从中创建 table

Powershell: Extract several strings from txt and create table out of it

我需要使用分布在许多 txt 文件中的值创建一个 csv 文件。这是其中一个 txt 文件的示例(它们都以相同的方式格式化并存储在一个文件夹中,比方说 c:\user\txtfiles):

System: asdf
Store: def
processid: 00001
Language: english
prodid: yellowshoes12
email: asdf@asdf.com
prodid: blueshoes34
some
other
text blabla

结果 csv 应如下所示(我添加了另一个示例 txt 中的值只是为了清楚):

processid, prodid
00001, yellowshoes12
00001, blueshoes34
00002, redtshirt12
00002, greensocks34

这意味着 txt 中的每个产品 ID 都应分配给 txt 中的一个 processid,并作为单行添加到 csv。

我尝试达到如下结果:

$pathtofiles = Get-ChildItem  c:\user\txtfiles | select -ExpandProperty FullName
$parsetxt = $pathtofiles | 
    ForEach { 
        $orderdata = Import-Csv $_  |
        Where-Object {($_ -like '*processid*') -or ($_ -like '*prodid*')} |
        foreach {
        
        write-output $orderdata -replace 'processid: ','' -replace 'prodid: ',''
        }
    }
      $orderdata

所以我的意图是隔离相关行,删除所有不需要的内容,将值分配给变量并从中构建一个 table。一个问题是,如果我将代码末尾的 $orderdata 替换为第一个 foreach 循环的末尾,则不会打印任何内容。但是经过一段时间的考虑,我不确定我的方法是否是一个好方法。因此,我们将不胜感激!

丹尼尔

我认为最好在遍历文件夹中的文件时使用 switch -Regex -File 结构来完成。

# get the files in the folder and loop over them
$result = Get-ChildItem -Path 'c:\user\txtfiles' -Filter '*.txt' -File | ForEach-Object {
    # the switch processes each line of a file and matches the regex to it
    switch -Regex -File $_.FullName {
        '^processid:\s+(\d+)' { $id = $matches[1] }
        '^prodid:\s+(\w+)' { [PsCustomObject]@{'processid' = $id; 'prodid' = $matches[1]}}
    }
} | Sort-Object processid, prodid

# output on console screen
$result

# output to CSV file
$result | Export-Csv -Path 'c:\user\txtfiles\allids.csv'

屏幕上的结果:

processid prodid       
--------- ------       
00001     blueshoes34  
00001     yellowshoes12
00002     greenshoes56 
00002     purpleshoes88