【问题标题】:Replacing many Words in a .docx File with Powershell用 Powershell 替换 .docx 文件中的许多单词
【发布时间】:2017-02-27 08:23:42
【问题描述】:

我想通过 Powershell 将我的 .docx 文件中的一些单词替换为另一个 .txt 文件中的一些字符串。 我打开并尝试用两个函数替换单词:

Function OpenWordDoc($Filename)
{
    $objWord = New-Object -comobject Word.Application  
    $objWord.Visible = $True;
    $objWord.Documents.Open($Filename)
    $objSelection = $objWord.Selection
    Return $objSelection; #return objWord
}

Function SearchAWord($Document,$search,$replacewithtext)
{ 
    $FindText = $search 
    $MatchCase = $False 
    $MatchWholeWord = $False 
    $MatchWildcards = $False 
    $MatchSoundsLike = $False 
    $MatchAllWordForms = $False 
    $Forward = $True 
    $Wrap = $wdFindContinue 
    $Format = $False 
    $wdReplaceNone = 1 
    $ReplaceWith = $replacewithtext
    $wdFindContinue = 1 

    $a=$Document.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,$wdReplaceNone) 
}

当我使用函数打开文档并尝试用字符串替换单词时,它可以工作,但是当我尝试更改更多单词时,它找不到使用函数的其他单词。 当我打开文档后直接搜索它们时,我可以找到它们。所以脚本总是只找到搜索的第一个单词。

我创建的函数有错吗?

编辑:我这样调用函数:

$doc=OpenWordDoc -Filename "C:\Users\$UserName\Desktop\test.docx"; #opens the Word-doc
for([int]$i=0; $i -ne 4;$i++)
{
  SearchAWord -Document $doc -search "string$i" -replacewithtext "test$i"
}

【问题讨论】:

  • 你怎么打电话给SearchAWord 可以添加这段代码吗?
  • @Richard 在 main-post 中添加了对这两个函数的调用

标签: string function powershell ms-word


【解决方案1】:

好的,我找到了答案:

当您想替换文档中的多个字符串时,您必须将$Document.Find.Execute 方法中最后一个Replace 变量的值更改为2,这会将函数WdReplace-Constant 设置为@987654325 @:

$Document.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,2)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-03-02
    • 2012-01-04
    • 1970-01-01
    • 2014-02-28
    • 1970-01-01
    • 2017-09-07
    相关资源
    最近更新 更多