首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在PowerShell中替换word文档中的多个字符串

在PowerShell中替换word文档中的多个字符串
EN

Stack Overflow用户
提问于 2020-12-10 11:54:05
回答 1查看 94关注 0票数 1

我尝试使用PowerShell替换word文档中的多个字符串,但在运行以下代码时只替换了一个字符串:

代码语言:javascript
复制
#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,第一个运行的调用可以工作,但是后续的调用不能。

例如,按原样运行会导致以下结果:

代码语言:javascript
复制
Input              Output
#ITEM1#            Should
#ITEM2#            #ITEM2#
#ITEM3#            #ITEM3#
#ITEM4#            #ITEM4#

我不确定我错过了什么,任何帮助都将不胜感激

EN

回答 1

Stack Overflow用户

发布于 2020-12-10 22:04:01

正如所建议的那样,光标似乎没有返回到文档的开头。我添加了以下代码:

代码语言:javascript
复制
Set-Variable -Name wdGoToLine -Value 3 -Option Constant
Set-Variable -Name wdGoToAbsolute -Value 1 -Option Constant

添加到我的脚本开头,然后:

代码语言:javascript
复制
$objSelection.GoTo($wdGoToLine, $wdGoToAbsolute, 1) > $null

作为我的FindAndReplace函数的第一行,现在它可以正常工作了。

也许有一个更优雅的解决方案,但这对我来说很有效。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/65228299

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档