在PowerShell中替换word文档中的多个字符串
我尝试使用PowerShell替换word文档中的多个字符串,但在运行以下代码时仅替换一个字符串:在PowerShell中替换word文档中的多个字符串,powershell,replace,ms-word,Powershell,Replace,Ms Word,我尝试使用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 = $tru
#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()
如果我注释掉find并替换第一个运行的函数,那么它可以工作,但后续调用不能
例如,按原样运行会导致:
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函数的第一行,现在它按预期工作
可能有一个更优雅的解决方案,但这对我来说很有效我假设它与
$forward=$true
相关。第一次查找/替换后,光标位于底部。我还没有掌握Word automation的最新进展,但我认为应该可以将搜索内容打包并/或将光标放回顶部。这两种方法都可以。谢谢你,这对我来说都不管用,但你的洞察力让我回答了这个问题。也许有一个更优雅的解决方案,但我会发布对我有效的方法。