powershell - 打开 Word 文档,根据搜索模式,转到该页面
问题描述
使用 PowerShell,我们使用以下命令成功提取了我们想要的数据:
Get-Content $SourceFileName |
Select-String -Pattern "search keywords"
要求:打开 Word 文档,搜索提供给功能的模式,如果找到转到该页面(这应该通过转到找到该搜索词的页面为最终用户打开 Word 文档)
这会打开 Word 文档,但不会转到正确的行(我想转到第 534 行)
Set-Variable -Name wdGoToLine -Value 3 -Option Constant Set-Variable -Name wdGoToAbsolute -Value 1 -Option Constant $t = $true $f = $false $a = New-Object -ComObject Word.Application $a.Visible = $true $b = $a.Documents.Open("D:\Scan.doc", $f, $t) $c = $a.Selection $d = $c.GoTo($wdGoToLine, $wdGoToAbsolute, 534)
这会将我带到正确的行,但不会为我打开 Word 文档:
Get-Content D:\Scan.doc -TotalCount 534 | Select-Object -Last 3;
上述命令的 LINE NUMBER 不同。Get-Content
一种模式给出 534,Word.Application
相同内容给出 1090。为什么会这样?
解决方案
这应该让你开始
# 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()
推荐阅读
- vue.js - 迭代时没有得到不同的类名
- asp.net-mvc - 我想在 mvc 的服务器路径中下载我的 Pdf 文件,请任何人指导我...用代码
- python - Boto3 使用 django 应用程序在本地和弹性 beantalk 上生成不同的链接
- ios - NSGenericException:此编码器要求从 initWithCoder 返回替换的对象
- angular - 通过按钮单击添加行
- c# - 多因素认证获取Sharepoint ClientContext后如何获取ProjectContext?
- r - 如何处理 knitr spin_child 中的编码
- javascript - 我的添加到购物车功能是替换购物车中的项目而不是添加
- pdf - 将 PDF/图像导入 Odoo 的 Python 脚本
- selenium - 如何在 CK 编辑器中单击链接图标