microsoft word powershell

PowerShell: Automating Search and Replace in Microsoft Word

I’m required to send various letters and internal memos on a schedule. I hate taking the boilerplate and going through and manually updating it to reflect the current period’s numbers, but there really aren’t ¬†many options. The folks receiving the communications expect it in a specific format, and they don’t like surprises. This means I’m using the same Word documents that have been used for 10+ years. I’ve tried to recreate them in Access or Excel and it never quite looks right. I found the solution in PowerShell here.

The idea is to take the boilerplate Word document and create a template where all of the variable elements have a unique name to be searched and replaced (ex: the date at the top of the letter reads CURRENTDATE). We then use a function, based on that link to the Microsoft explanation, to switch each variable element to what we want. So, for CURRENTDATE, we’d replace it with¬†(get-date).tostring(‘MMMM dd, yyyy’) to get February 13, 2017.

Anyway, I’m going to change my processes to use this all over the place.

#function that does the search and replace.
function replaceword ($FindText, $ReplaceText)
    $ReplaceAll = 2
    $FindContinue = 1
    $MatchCase = $False
    $MatchWholeWord = $True
    $MatchWildcards = $False
    $MatchSoundsLike = $False
    $MatchAllWordForms = $False
    $Forward = $True
    $Wrap = $FindContinue
    $Format = $False

      $ReplaceText,$ReplaceAll) | out-null

#creating the word com object
$objWord = New-Object -ComObject word.application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open("Payment.doc")
$objSelection = $objWord.Selection

#function call
replaceword "CURRENTDATE" (get-date).tostring('MMMM dd, yyyy')