Home > Microsoft Office > Replacing text in Word documents through PowerShell

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.

word-01

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.

word-02

Click here to download the Script.

Rating 3.00 out of 5
[?]
Categories: Microsoft Office Tags:
  1. Krisitan Nagel
    February 6th, 2009 at 09:12 | #1

    Thanks Niklas, this was indeed really useful!

  2. dmtelf
    March 11th, 2009 at 12:19 | #2

    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?

  3. March 15th, 2009 at 23:19 | #3

    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

  1. No trackbacks yet.

Spam Protection by WP-SpamFree