2017-08-24 226 views
0

簡而言之,我有一個我需要的Excel文件: - 只有2列(計算機名,結果) - 只需要包含特定項目的行(IE。從DriveLetter開始:\, HKLM,%windir%等)導入CSV匹配多個關鍵字

我只是不確定適當的關鍵字語法在這裏。原始文件是一個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 

回答

0

我發現了這個問題。我需要的_.Results .....和我需要匹配$ Filter

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