2017-02-15 103 views
0

我在網上找到了一個很棒的Powershell腳本,讓我們搜索Excel文檔的內容以查找特定單詞,並根據需要對其進行了修改。查找MS Word的方法

現在我想添加用於搜索Word文檔內容的功能,但是我正在努力弄清楚我需要使用的方法(?)。

請原諒我,如果我得到關於類和方法的術語錯誤,這對我來說是新的領域。

這個爲腳本的現有代碼:

$SearchDest = Read-Host "Where do you want to search?" 
$Destination = 'C:\temp' 
$SearchText = 'myword' 
$Excel = New-Object -ComObject Excel.Application 

$Files = Get-ChildItem "$SearchDest\*.xlsx" | Select-Object -Expand FullName 
$counter = 1 

ForEach($File in $Files) { 

    Write-Progress -Activity "Checking: $file" -Status "File $counter of $($files.count)" ` 
        -PercentComplete ($counter * 100/$files.Count) 

    $Workbook = $Excel.Workbooks.Open($File) 

    If($Workbook.Sheets.Item(1).Range("A:Z").Find($SearchText)) { 
     $Workbook.Close($false) 
     Copy-Item -Path $File -Destination $Destination 
     "Copied $file to $destination" 
     break 
    } 

    $Workbook.Close($false) 
    $counter++ 
} 

,我試圖找出相當於$Excel.Workbooks.Open($File)等是。

+0

您是否嘗試過尋找的Word基於腳本,讓你正在尋找方法? – Matt

回答

2

這裏有一個解決方案,這將遍歷的.DOCX文件的文件夾和搜索這些文件的單詞或短語:

[void][Reflection.Assembly]::LoadWithPartialName("Microsoft.Office.Interop.Word") 

# create a word app object 
Write-Host 'creating word app object' 

$word = New-Object -ComObject Word.Application 
$word.Visible = $True 

$docs = Get-ChildItem -Path 'C:\Path\To\WordDocs\' -Filter '*.docx' | select -ExpandProperty Fullname 

# options for the search 
$findText   = 'DataFolder' # alter this to find the word you're interested in 
$matchCase   = $false 
$matchWholeWord = $true 
$matchWildCards = $false 
$matchSoundsLike = $false 
$matchAllWordForms = $false 
$forward   = $true 
$wrap    = 1 

$docs | ForEach-Object { 
    $docPath = $_ 
    Write-Host "opening $docPath" -NoNewline 

    $doc = $word.Documents.Open($docPath) 

    $range = $doc.Content 
    [void]$range.MoveStart() 

    $wordFound = $range.Find.Execute($findText,$matchCase,$matchWholeWord,$matchWildCards,$matchSoundsLike,$matchAllWordForms,$forward,$wrap) 

    if ($wordFound) { 
    # do something meaningful here 
    } 
    # for now, we'll output a list of files and if the word was found 
    [PSCustomObject]@{ 
    FilePath = $docPath 
    WordToFind = $findText 
    WordFound = $wordFound 
    } 

    $doc.Close() 
} 

# clean up after ourselves 
$null = [System.Runtime.InteropServices.Marshal]::ReleaseComObject([System.__ComObject]$word) 
[GC]::Collect() 
[GC]::WaitForPendingFinalizers() 
Remove-Variable word 
+0

嗨Techspud,謝謝你爲我提供了一個解決問題的答案。你能告訴我你是如何找出使用哪種方法的?列表中是否有列出word.application.documents等的列表? – MondQ

+0

Google&StackOverflow :)。不完全是。 Google如何在word doc中查找字符串,並且有一個腳本專家文章提供了一些細節。此外,循環,打開/關閉和清理也從以前的Google&SO搜索中收集。如果這回答你的問題,你能標記爲完整嗎? – TechSpud

+0

完成。謝謝。 – MondQ