Replacing text in Word documents through PowerShell
In a previous migration project, we had some issues with Word documents, actually a couple of thousand Word documents containing Server names pointing to the old servers.. In other words, after the migration, all these word documents would point to the wrong server. Changing this manually would take weeks. Changing the documents through PowerShell would take a few minutes.
In this post, I’m going to demonstrate how you can manipulate text in Word documents through PowerShell. Let’s say we have a document containing the Lyrics to Johhny Cash – Ring of Fire.
Lets replace the word “ring of fire” with “Chuck Norris RoundHouse Kick”
The function used is pretty straight forward. First setting up the variables required by the Execute() method and then connecting to the document that we want to manipulate.
function Replace-Word ([string]$Document,[string]$FindText,[string]$ReplaceText) {
#Variables used to Match And Replace
$ReplaceAll = 2
$FindContinue = 1
$MatchCase = $False
$MatchWholeWord = $True
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $FindContinue
$Format = $False
$Word = New-Object -comobject Word.Application
$Word.Visible = $False
$OpenDoc = $Word.Documents.Open($Document)
$Selection = $Word.Selection
$Selection.Find.Execute(
$FindText,
$MatchCase,
$MatchWholeWord,
$MatchWildcards,
$MatchSoundsLike,
$MatchAllWordForms,
$Forward,
$Wrap,
$Format,
$ReplaceText,
$ReplaceAll
)
$OpenDoc.Close()
}
Running the function would look something like this:
Replace-Word C:\Ring Of Fire.docx "ring of fire" "Chuck Norris RoundHouse Kick"Here’s what happend to the Document when I ran the function.
Click here to download the Script.
[?]

Thanks Niklas, this was indeed really useful!
This is a very handy script!
Is it possible to insert a page-break in a Word document using PowerShell after e.g. the end of a paragraph?
Hi.
I wrote a new post regarding the Scenario that you described. I hope you find it useful. Though I recommend that you take a backup of your documents before testing, since I’ve only tested the script on “Test” documents.
Regards
Goude