Reputation: 3046
I want to replace some Words in my .docx File with some strings from another .txt File via Powershell. I open and try to replace words with two functions:
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)
}
When I open the Doc with with the function and try to replace a Word with a string it works, but when I try to change more Words it does not find other Words with the function. I can find them when I search for them directly after opening the doc. So the script allways only finds the first word searched.
Did I create the functions wrong?
Edit: I'm calling the functions like this:
$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"
}
Upvotes: 0
Views: 3115
Reputation: 3046
Ok I found the answer:
When you want to replace more than one string in the Doc you have to change the value of the last Replace
variable in the $Document.Find.Execute
methode to 2
, this sets the function WdReplace-Constant
to "replace all"
:
$Document.Find.Execute($FindText,$MatchCase,$MatchWholeWord,$MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,$Wrap,$Format,$ReplaceWith,2)
Upvotes: 1