优化代码以在Word文档中搜索多个关键字

时间:2018-09-12 16:32:40

标签: powershell

下面的代码可以很好地工作,并从Word文档中提取所需的部分。我们必须在文档中一个接一个地搜索将近50个关键字,如何才能优化此代码。因为使用当前方法,我们搜索一个关键字,然后再次打开文档并再次搜索。这将花费很长的执行时间。有任何建议。

以下代码:提取两个HEADINGS之间的文本,如何对其进行优化,以便我们可以搜索50个关键字...一次打开文档并扫描至结束。

function ExtractSectionsFromWordDoc{
Param([string]$SourceFile, [string]$Category, [string]$SearchKeyword1, [string]$SearchKeyword2, [string]$TableName)

$word = New-Object -ComObject Word.Application
$word.Visible = $false
$doc = $word.Documents.Open($SourceFile,$false,$true)
$sel = $word.Selection 
$paras = $doc.Paragraphs 

foreach ($para in $paras) 
{ 
    $style = $para.Style 
    If ($style.NameLocal -eq "Heading 2") 
    { 

        if ($para.Range.Text -match $SearchKeyword1)
        {
            $startPosition = $para.Range.Start
            Write-Host $startPosition
        }
        if ($para.Range.Text -match $SearchKeyword2)
        {
            $endPosition = $para.Range.Start
            Write-Host $endPosition
            break
        }
    }
} 
[array]$content=New-Object System.Collections.ArrayList
$content=$doc.Range($startPosition, $endPosition).text
$content = $content -replace "'", ""

# cleanup com objects
$doc.Close()
$word.Quit()
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($doc) | Out-Null
[System.Runtime.Interopservices.Marshal]::ReleaseComObject($word) | Out-Null
[System.GC]::Collect()
[System.GC]::WaitForPendingFinalizers()
}

0 个答案:

没有答案