2017-02-15 141 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