导入CSV匹配多个关键字

时间:2017-08-24 16:02:17

标签: match keyword-search import-csv

简而言之,我有一个我需要的excel文件: - 仅2列(ComputerName,结果) - 只需要包含特定项目的行(IE。以DriveLetter开头:\,HKLM,%windir%等)

我只是不确定这里正确的关键字语法。原始文件是xlsx。 请原谅我的剧本粗糙。为了让它发挥作用,我收集了点点滴滴。

    #File Import to Variable
Function Remove-File($fileName) {
 if(Test-Path -path $fileName) { Remove-Item -path $fileName }
}

$excelFile = ".\Computers.xlsx"
if(Test-Path -path $excelFile) {
 $csvFile = ($env:temp + "\" + ((Get-Item -path $excelFile).name).Replace(((Get-Item -path $excelFile).extension),".csv"))

 Remove-File $csvFile

 $excelObject = New-Object -ComObject Excel.Application   
 $excelObject.Visible = $false 
 $workbookObject = $excelObject.Workbooks.Open($excelFile) 
 $workbookObject.SaveAs($csvFile,6) # http://msdn.microsoft.com/en-us/library/bb241279.aspx
 $workbookObject.Saved = $true
 $workbookObject.Close()
 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($workbookObject) | Out-Null
 $excelObject.Quit()
 [System.Runtime.Interopservices.Marshal]::ReleaseComObject($excelObject) | Out-Null
 [System.GC]::Collect()
 [System.GC]::WaitForPendingFinalizers() 

 $spreadsheetDataObject = Import-Csv -path $csvFile # Use the $spreadsheetDataObject for your analysis

 Remove-File $csvFile
}

#Filter Out All Columns except ComputerName, Results and subseqently create a CSV file
$PathCSV = ".\Computers.csv"
$spreadsheetDataObject | Select-Object ComputerName,Results | Export-Csv -Path $PathCSV -NoTypeInformation

$Keywords = "*HKLM*","*C:\*","*%windir%*"
$Filter = "($(($Keywords|%{[RegEx]::Escape($_)}) -join "|"))"


Import-CSV $PathCSV | Where-Object{$_Results -match $Keywords} | Export-Csv -Path ".\Computers2.csv" -NoTypeInformation 

1 个答案:

答案 0 :(得分:0)

我发现了这个问题。我需要_.Results .....我需要-match $ Filter

Import-CSV $PathCSV | Where-Object{$_.Results -match $Filter} | Export-Csv -Path ".\Computers2.csv" -NoTypeInformation