Powershell匹配当前行和下一行然后输出文件

Powershell to match the current line and next line then out-file

我正在尝试提取数据:

第 1 行 = 报告 ID + 第 2 行 = "Machine no" + 第 3 行 = 离线

然后Out-File到一个新文件。

示例数据

报告 ID 第 1 页

机号 1234

        其他
            12
        离线
            12
        其他
            23
        离线
            37
        其他
            89
        离线
            65

我要查找的结果在处理后如下所示:

报告 ID 第 4 页

    机号 1234
        离线
            12
        离线
            37
        离线
            65

您可以使用带有 -Context 参数的 Select-String cmdlet 来搜索文件,然后 select 您希望从搜索中返回多少行上下文信息。

例如,如果我们将您的输入文件存储在一个名为 $input 的变量中,如下所示:

$inputFile= Get-Content C:\Path\To\YourFile.txt
$inputFile| Select-string 'machine no'
>Machine no  1234  

然后我们可以找到短语 'offline' 的匹配项:

$inputFile| Select-String offline -Context 0,1

这表示我希望你搜索单词 'offline' 并给我继续它的零行,以及它之后的一行,给我们这个输出:

>         offline
              12
>         offline
              37
>         offline
              65

我们可以将所有这些放在一起来构建它并生成一个新的输出文件,如下所示。

$out= ''
$out += $inputFile| Select-string 'machine no'
$out += "`n"
$out += $inputFile| Select-String offline -Context 0,1 | ForEach-Object {$_.Context.DisplayPostContext}

#Resulting file would look this, just the name of the machine and then the number of each offline...uh, whatever it is.
    Machine no  1234    
        12             37             65

如果我是你,我会调整此流程来制作 PowerShell 对象和属性,如下所示:

$Report = [pscustomobject]@{ID='';MachineNo='';OfflineMembers=@()}
$Report.ID = ($inputFile | select-string page -Context 0 ).ToString().Split('page')[-1]
$Report.MachineNo = ($inputFile | Select-string 'machine no').ToString().Trim().Split()[-1]
$Report.OfflineMembers = $inputFile | Select-String offline -Context 0,1 | ForEach-Object {
            [pscustomobject]@{Value='Offline';ID=$_.Context.DisplayPostContext.Trim()}
            }

>$Report

ID MachineNo OfflineMembers                                                             
-- --------- --------------                                                             
1 1234      {@{Value=Offline; ID=12}, @{Value=Offline; ID=37}, @{Value=Offline; ID=65}}
 $Report.OfflineMembers
Value   ID
-----   --
Offline 12
Offline 37
Offline 65