过滤CSV回车

时间:2017-08-24 20:47:48

标签: powershell csv filtering

尝试弄清楚如何过滤特定CSV中的项目。

CSV内容:

ComputerName,Results
computerA      ," KB00000 is not installed 
c:\SomeTestFile Version is 2
c:\SomeTestFile Version is 11.0"
ComputerB   ,%windir%\somefile.exe is Version 1.2

我需要先根据第二列中的回车过滤,然后过滤不同的参数,例如"是版本10和#34;或" KB00000缺失"进行。

CSV中的预期输出:

ComputerName,Results
computerA ,c:\SomeTestFile Version is 2
computerA ,c:\SomeTestFile Version is 11.0
ComputerB ,%windir%\somefile.exe is Version 1.2

有一个编码块。我可以导入文件,但仍然会过滤。

$CSV = Import-Csv File.csv 

1 个答案:

答案 0 :(得分:0)

使用您给定的csv

这个脚本:

## Q:\Test\2017\08\24\SO_45870618.ps1
$FileIn  = '.\FileIn.Csv'
$FileOut = '.\FileOut.Csv'

$Csv = Import-Csv $FileIn
$Csv

$CsvNew = ForEach ($Row in $Csv) {
    If (!($Row.ComputerName)){
        If ($Last) {$Row.ComputerName = $Last}
    }
    $Last = $Row.ComputerName
    ForEach ($line in ($Row.Results -Split('\r?\n')) ){
        If ($line -NotMatch '^\s*KB\d+\s+is'){
            [PSCustomObject]@{ComputerName = $Last.Trim()
                              Results = $line}
        }
    }
}
"------------"
$CsvNew 
$CsvNew | Export-Csv $FileOut -NoTypeInformation

将有此输出:

> Q:\Test\2017\08\24\SO_45870618.ps1

ComputerName Results
------------ -------
computerA     KB00000 is not installed ...
ComputerB    %windir%\somefile.exe is Version 1.2
------------
computerA    c:\SomeTestFile Version is 2
computerA    c:\SomeTestFile Version is 11.0
ComputerB    %windir%\somefile.exe is Version 1.2

产生的FileOut.csv:

> gc .\FileOut.Csv
"ComputerName","Results"
"computerA","c:\SomeTestFile Version is 2"
"computerA","c:\SomeTestFile Version is 11.0"
"ComputerB","%windir%\somefile.exe is Version 1.2"