首页 > 解决方案 > 打开 Word 文档,根据搜索模式,转到该页面

问题描述

使用 PowerShell,我们使用以下命令成功提取了我们想要的数据:

Get-Content $SourceFileName |
    Select-String -Pattern "search keywords"

要求:打开 Word 文档,搜索提供给功能的模式,如果找到转到该页面(这应该通过转到找到该搜索词的页面为最终用户打开 Word 文档)

上述命令的 LINE NUMBER 不同。Get-Content一种模式给出 534,Word.Application相同内容给出 1090。为什么会这样?

标签: powershell

解决方案


这应该让你开始

# set these to your liking
$file = "D:\Scan.docx"
$textToFind = "find me"
$matchWildcards = $false 
$matchCase = $true

# some Word constants
$wdFindStop = 0
$wdActiveEndPageNumber = 3
$wdStory = 6
$wdGoToPage = 1
$wdGoToAbsolute = 1

# Documents.Open switches
$ReadOnly = $false  # when ReadONly was set to $true, it gave me an error on 'Selection.GoTo()' 
                    # 'This method or property is not available because this command is not available for reading.' 
$ConfirmConversions = $false

$word = New-Object -ComObject Word.Application
$word.Visible = $true
$doc = $word.Documents.Open($file, $ConfirmConversions, $ReadOnly)
$range = $doc.Content
$range.Find.ClearFormatting(); 
$range.Find.Forward = $true 
$range.Find.Text = $textToFind
$range.Find.Wrap = $wdFindStop
$range.Find.MatchWildcards = $matchWildcards
$range.Find.MatchCase = $matchCase
$range.Find.Execute()
if ($range.Find.Found) {
    # get the pagenumber
    $page = $range.Information($wdActiveEndPageNumber)
    Write-Host "Found '$textToFind' on page $page" -ForegroundColor Green
    [void] $word.Selection.GoTo($wdGoToPage, $wdGoToAbsolute, $page)
}
else {
    Write-Host "'$textToFind' not found" -ForegroundColor Red
    [void] $word.Selection.GoTo($wdGoToPage, $wdGoToAbsolute, 1)
}

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

推荐阅读