Using "Open Application" for MS Word where the filename is in a variable

Thanks Allan I understand.

I managed to find the following Powershell script that does the job nicely based on this Scripting Office with PowerShell: Finding and Replacing Text in Word Documents

$Word = New-Object -ComObject Word.Application

# Specify the path to the specific Word document you want to open
$WordFilePath = "C:\path\to\your\document.docx"

$FindText = "10 Main Street" # <= Find this text
$ReplaceText = "22 Industrial Park Road" # <= Replace it with this text

$MatchCase = $false
$MatchWholeWord = $true
$MatchWildcards = $false
$MatchSoundsLike = $false
$MatchAllWordForms = $false
$Forward = $false
$Wrap = 1
$Format = $false
$Replace = 2

# Open the specific document
$Document = $Word.Documents.Open($WordFilePath)

# Find and replace the text using the variables we just set up
$Document.Content.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $Wrap, $Format, $ReplaceText, $Replace)

# Save and close the document
$Document.Close(-1) # The -1 corresponds to https://docs.microsoft.com/en-us/office/vba/api/word.wdsaveoptions

$Word.Quit()

1 Like