2017-02-15 7 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では単語のdocで文字列を検索する方法と、Scripting Guysの記事で詳細を説明しています。さらに、以前のGoogleとSOの検索でもループ、開閉、クリーンアップが行われました。これであなたの質問に答えることができますか? – TechSpud

+0

完了。ありがとうございました。 – MondQ

関連する問題