Powershell search matching string in word document

后端 未结 3 1990
暖寄归人
暖寄归人 2021-01-13 11:41

I have a simple requirement. I need to search a string in Word document and as result I need to get matching line / some words around in document.

So far, I could s

3条回答
  •  失恋的感觉
    2021-01-13 12:04

    Good answer from @Matt. I improved it a little (new PowerShell version have problems with the given array. And to search big amount of documents it runs out of memory. Here is my improved version:

    #ERROR REPORTING ALL
    Set-StrictMode -Version latest
    $path     = "c:\Temp"
    $files    = Get-Childitem $path -Include *.docx,*.doc -Recurse | Where-Object { !($_.psiscontainer) }
    $output   = "c:\temp\wordfiletry.csv"
    $application = New-Object -comobject word.application
    $application.visible = $False
    $findtext = "First"
    $charactersAround = 30
    $results = @{}
    
    Function getStringMatch
    {
        # Loop through all *.doc files in the $path directory
        Foreach ($file In $files)
        {
            $document = $application.documents.open($file.FullName,$false,$true)
            $range = $document.content
    
            If($range.Text -match ".{$($charactersAround)}$($findtext).{$($charactersAround)}"){
                 $properties = @{
                    File = $file.FullName
                    Match = $findtext
                    TextAround = $Matches[0] 
                 }
                 $results += @(New-Object -TypeName PsCustomObject -Property $properties)
            }
            $document.close()
        }
    
        If($results){
            $results | Export-Csv $output -NoTypeInformation
        }
        $application.quit()
    }
    getStringMatch
    import-csv $output
    

提交回复
热议问题