Search code examples
powershellms-wordcom

Programmatically remove all hidden text in a Word document


Using PowerShell, I need to write a script which would remove all hidden text of a Word Document.

Here is what I have so far :

$WordDocument = Get-Item "C:\MyWordDocument.docx"

$word_app = New-Object -ComObject Word.Application
$word_app.Visible = $false

$document = $word_app.Documents.Open($WordDocument.FullName)

$objSelection = $word_app.Selection 
$objSelection.Font.Hidden = $True

$FindText = "" # search on formatting only (according to MS doc)
$wdFindContinue = 1
$ReplaceAll = 2
$MatchCase = $False 
$MatchWholeWord = $False 
$MatchWildcards = $False 
$MatchSoundsLike = $False 
$MatchAllWordForms = $False 
$Forward = $True 
$Wrap = $wdFindContinue 
$Format = $True # ?
$ReplaceWith = "" 

$a = $objSelection.Find.Execute($FindText,$MatchCase,$MatchWholeWord, ` 
    $MatchWildcards,$MatchSoundsLike,$MatchAllWordForms,$Forward,` 
    $Wrap,$Format,$ReplaceWith,$ReplaceAll) 
$document.Save()
$document.Close()

$word_app.Quit()

It does not work, and I cannot figure out why.

Any idea ?


Solution

  • The mistake is where you set the search filter to find hidden text. Instead of $objSelection.Font.Hidden = $True (this actually hides the currently selected text) you need to set the property on the $objSelection.Find object:

    $objSelection.Find.Font.Hidden = $True