Link to home
Start Free TrialLog in
Avatar of Fr. Vandecan
Fr. VandecanFlag for Belgium

asked on

Replace [fields] on word htm file : how to ?

I have a htm file created with Word.
This file contains a table (see attached). It's in french. no worry. the purpose is to replace [fields] to real values.
To achieve this, my code is this :
$Datas =  (Select-Xml -Path $strFullFile -XPath //body/h4).node.InnerText}

            $datas = $Datas -replace "[EndOfContract]", $DateFrom
            $datas = $Datas -replace "[TypeOfJcDept]", $strMailboxType
            $datas = $Datas -replace "[JcDEPTName]", $strMailboxAlias
en so forth

this does not seems to work as the code seems to completely destroy the htm file.

If I analyze te situation if each letter of [EndOfCOntract] with is seen on the file is replaced. I was expecting the ONLY [EndOFContrat] Beeing replaced by $dateFrom.

so seems that the command is totally wrong....
what else?
any idea? other method to achieve same result?

Many tks.
Avatar of J0rtIT
Flag of Venezuela, Bolivarian Republic of image

can you attach a dummy html file with the fields? because it's required to do the testing of the code.

The issue is that the -replace operator uses regex to search for matching text, and brackets ("[" and "]") have a special meaning in regex.  The following would all work correctly.
$datas = $Datas -replace "\[EndOfContract]", $DateFrom
$datas = $Datas -replace "\[TypeOfJcDept]", $strMailboxType
$datas = $Datas -replace "\[JcDEPTName]", $strMailboxAlias

Open in new window

For those, I've just escaped (with a backslash, "\") the opening bracket.  You could escape the closing bracket as well, but with the opening bracket escaped, the closing bracket is interpreted literally without any special significance.  You can read here for more info on regex.

If you have trouble with remembering which characters need to be escaped to be interpreted literally when searching for a match, you can use something like the following.  The [regex]::escape() static method automatically escapes any characters that could have special significance.
$field = "[EndOfContract]"
$regexpattern = [regex]::escape($field)
$datas = $Datas -replace $regexpattern, $DateFrom

Open in new window

Avatar of Fr. Vandecan


Thanks. I have seen indeed that having put my fieldname in [], means for Powershell replace that I'm expecting that every char inside [] need to be replaced ...
I have now suppress those [] and it work's perfectly.

PS Even replacing [] by () does something else. It's replacing string inside () but not the()...

Thanks !
Avatar of footech
Flag of United States of America image

Link to home
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial