在使用PowerShell搜索了另一个名为Base的特定模式后,我试图在不同的行中找到一组特定的字符串,如Test2、Test3和Test4。为了同时生成Base、Test2、Test3和Test4行内容的报告,我编写了如下代码:然而,它并不总是得到所需的输出。文件数据如下所示
Base: some text
some line here
some line here
Test2: another text
Test3: other text
Test4: different text
some lines here
some lines here
some lines here
Base: some text
some line here
some line here
Test2: another text
Test3: other text
Test4: different text
some lines here
some lines here
some lines here
some lines here
.............
.............
$data = Get-Content $file
$req_data = $data |where {$_.Contains("Base") -or $_.Contains("Test2") -or $_.Contains("Test3") -or $_.Contains("Test4")}
$bases_data = $data |where {$_.Contains("Base")}
foreach ($basedata in $bases_data)
{
$find_alias = ($req_data |select-string "^${basedata}$" -context (0.10)).Context.PostContext
$final_data = "" | select Base, Test2, Test3, Test4
$temp.Base = $basedata
$temp.Test2 = ($find_alias |select-string "Test2").Tostring()
$temp.Test3 = ($find_alias |select-string "Test3").Tostring()
$temp.Test4 = ($find_alias |select-string "Test4").Tostring()
$temp
}
预期产出应为:
Base Test2 Test3 Test4
Base line data Test2 line data Test3 line data Test4 line data
...... ......... ....... ....
1条答案
按热度按时间gojuced71#
假设数据在文件中。您可以使用
Select-String
为任何字符串挑选相应的行。我没有在格式上做太多的工作。但这也是可行的。希望能有所帮助。