powershell - 在 PowerShell 中替换 word doc 中的多个字符串
问题描述
我正在尝试使用 PowerShell 替换 word 文档中的多个字符串,但在运行以下代码时只替换了一个字符串:
#Includes
Add-Type -AssemblyName System.Windows.Forms
#Functions
#Function to find and replace in a word document
function FindAndReplace($objSelection, $findText,$replaceWith){
$matchCase = $true
$matchWholeWord = $true
$matchWildcards = $false
$matchSoundsLike = $false
$matchAllWordForms = $false
$forward = $true
$wrap = [Microsoft.Office.Interop.Word.WdFindWrap]::wdReplaceAll
$format = $false
$replace = [Microsoft.Office.Interop.Word.WdFindWrap]::wdFindContinue
$objSelection.Find.Execute($findText,$matchCase,$matchWholeWord,$matchWildcards,$matchSoundsLike,$matchAllWordForms,$forward,$wrap,$format,$replaceWith, $replace) > $null
}
$item1 = "Should"
$item2 = "this"
$item3 = "work"
$item4 = "?"
$fileName = "NewFile"
#Opens a file browsers to select a word document
$FileBrowser = New-Object System.Windows.Forms.OpenFileDialog -Property @{
InitialDirectory = [Environment]::GetFolderPath('Desktop')
Filter = 'Documents (*.docx)|*.docx'
}
Write-Host "Select word template file"
$FileBrowser.ShowDialog()
$templateFile = $FileBrowser.FileName
$word = New-Object -comobject Word.Application
$word.Visible = $false
$template = $word.Documents.Open($templateFile)
$selection = $template.ActiveWindow.Selection
FindAndReplace $selection '#ITEM1#' $item1
FindAndReplace $selection '#ITEM2#' $item2
FindAndReplace $selection '#ITEM3#' $item3
FindAndReplace $selection '#ITEM4#' $item4
$fileName = $fileName
$template.SaveAs($fileName)
$word.Quit()
如果我注释掉 FindAndReplace 运行的第一个工作,但后续调用没有。
例如,按原样运行会导致:
Input Output
#ITEM1# Should
#ITEM2# #ITEM2#
#ITEM3# #ITEM3#
#ITEM4# #ITEM4#
我不确定我错过了什么,任何帮助将不胜感激
解决方案
正如建议的那样,光标似乎没有返回到文档的开头。我添加了以下代码:
Set-Variable -Name wdGoToLine -Value 3 -Option Constant
Set-Variable -Name wdGoToAbsolute -Value 1 -Option Constant
在我的脚本的开头,并且:
$objSelection.GoTo($wdGoToLine, $wdGoToAbsolute, 1) > $null
作为我的 FindAndReplace 函数的第一行,现在它按预期工作。
可能有一个更优雅的解决方案,但这对我有用
推荐阅读
- php - 使用 AbstractNormalizer::ATTRIBUTES 规范化嵌套对象
- ruby-on-rails - Docker Web 映像现在可以与 rspec gem 一起使用
- python - 在 TensorFlow Hub 模型上使用 TensorBoard 时出现 InvalidArgumentError
- android - 每次在带有导航的底部导航视图中选择一个选项卡时,都会创建片段的新实例
- reactjs - React Router - 在变量或组件中分组路由
- java - 如何避免多次空检查,如果需要在每次检查后做一些事情
- swift - 为什么从不调用 DispatchGroup deinit?
- java - 已解析的 Groovy 脚本的(反)序列化
- apache-nifi - 有没有办法以编程方式接收 NiFi 远程进程组的目标 uri?
- string - 如何转义 SPARQL 字符串中的括号?