Share via


PowerShell Trick: Search & highlight text in MS Word

Recently there was an interesting scenario asked in the PowerShell Facebook Group.

A script that takes a list of words (in Notepad, CSV, whatever) and highlights those words in a Microsoft Word doc. (.docx).

Interesting! Often there are solutions already published for this sort of thing. Sure enough, a search found several. Of these, the best seemed to be on CodeProject.

The technique was adapted into the PowerShell code snippet below:


$objWord = New-Object -ComObject word.application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open("C:\temp\test.docx")
 
 
$FindText = "document"
 
  foreach ($docrange in $objDoc.Words)
  {
     if ($docrange.Text.Trim() -eq $FindText)
     {
        $docrange.highlightColorIndex = [Microsoft.Office.Interop.Word.WdColorIndex]::wdYellow 
     }
  }

It works. Below is a pic showing the highlighted entries after the script was run:

Cheers!