Home > Mobile >  How to use Powershell to replace text in Word which is in single line and different line?
How to use Powershell to replace text in Word which is in single line and different line?

Time:05-23

So I want to edit a .docx file using PowerShell: First Name, Last Name, Address, Salary, Starting Day etc. I am a beginner in PowerShell so I'm not too sure about the code; so, firstly I wanted to run something that will change all the instances of the full name in the Word template.

$objWord = New-Object -ComObject word.application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open("C:\...")
$objSelection = $objWord.Selection

$FindText = "<First Name> <Last Name>"
$ReplaceText = "Someone Something"

$ReplaceAll = 2
$FindContinue = 1
$MatchCase = $False
$MatchWholeWord = $True
$MatchWildcards = $False
$MatchSoundsLike = $False
$MatchAllWordForms = $False
$Forward = $True
$Wrap = $FindContinue
$Format = $False

$objSelection.Find.Execute($FindText,$MatchCase,
  $MatchWholeWord,$MatchWildcards,$MatchSoundsLike,
  $MatchAllWordForms,$Forward,$Wrap,$Format,
  $ReplaceText,$ReplaceAll)

So this works for all instances of the First Name and Last Name when they are in the same line, but not when I have them in different lines underneath each other like this:

First Name

Last Name

How do I write my code so that this sort of example is included aswell?

CodePudding user response:

Found a workaround seems to be working now perfectly well. Hope this helps to someone

$objWord = New-Object -ComObject word.application
$objWord.Visible = $True
$objDoc = $objWord.Documents.Open("Path")
$objSelection = $objWord.Selection

function wordSearch($currentValue, $replaceValue){
    $objSelection = $objWord.Selection
    $FindText = $currentValue
    $MatchCase = $false
    $MatchWholeWord = $true
    $MatchWildcards = $false
    $MatchSoundsLike = $false
    $MatchAllWordForms = $false
    $Forward = $true
    $wrap = $wdFindContinue
    $wdFindContinue = 1
    $Format = $false
    $ReplaceWith = $hash[$value]
    $ReplaceAll = 2

    $objSelection.Find.Execute($FindText, $MatchCase, $MatchWholeWord, $MatchWildcards, $MatchSoundsLike, $MatchAllWordForms, $Forward, $wrap, $Format, $ReplaceWith, $ReplaceAll)
    }

$hash = @{"<First Name>" = "Value1"; "<Last Name>"="Value2"; "<Job>"="Value3"}

foreach($value in $hash.Keys) {
    $currentValue = $value
    $replaceValue = $hash[$value]

    wordSearch $currentValue $replaceValue

    }
  • Related