I have an XML file with some specific keywords I need to replace, here's an example:
<?xml version="1.0" encoding="utf-8"?>
<!--Exported at 23-09-2019 10:01:23-->
<DEFTABLE xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="Folder.xsd">
<SMART_FOLDER JOBISN="1" APPLICATION="6261" SUB_APPLICATION="R001J_CMNOK" JOBNAME="6261_R001J_CMNOK" DESCRIPTION="Snapshot des jobs not ok de control-m ds intraprd2" >
<JOB JOBISN="2" APPLICATION="6261" SUB_APPLICATION="R001J_CMNOK" MEMNAME="R010J.BAT" JOBNAME="6261R001J010J_CMNOK" DESCRIPTION="[07:00] Chargement job ended_notok" CREATED_BY="Graf">
<VARIABLE NAME="%%LIBMEMSYM" VALUE="%%VG_LIBMEMSYM./CTM.var" />
<RULE_BASED_CALENDARS NAME="*" />
</JOB>
</SMART_FOLDER>
</DEFTABLE>
I need to replace "Recette" with "Production" and "6261_R001J_CMNOK" with "6261_P001J_CMNOK" and write the new XML in a copy of the file I made earlier like this:
$CreateFileName = $($OriginalXMLFilePath -replace ".{4}$") + "_" + $(Get-Date -UFormat "%Y-%m-%d_%H%M%S") + ".xml"
$CopyFile = Copy-Item $OriginalXMLFilePath -Destination $CreateFileName -Force
# New file name is 6261_XML_2019-11-18_135100.xml
I made the following variables:
$A_Lookup = @("Recette","6261_R001J_CMNOK")
$B_Replace = @("Production", "6261_P001J_CMNOK")
Here was the rest of my code to replace the XML:
$Read = Get-Content -Path $OriginalXMLFilePath
for ($i = 0; $i -lt $A_Lookup.length; $i++) {
$Read = $Read -replace $A_Lookup[$i], $B_Replace[$i]
}
Remove-Item -Path $OriginalXMLFilePath -Force
Add-Content -Path $OriginalXMLFilePath -Value $Read -Force
Problem is, there was around 25+ items after the @(
and that's not very optimized when we need to add more content there. So I decided to make a lookup table instead:
$lookupTable = @{
"Recette" = "Production"
"6261_R001J_CMNOK" = "6261_P001J_CMNOK"
}
But now my main issue is that the part of my code that would replace $A_Lookup
by $B_Replace
doesn't work anymore. I tried the "Solution 4" on this page and other solutions around Stack Overflow but none really worked for me. What's blocking me the most is that I can't seem to write anything into the new XML file.
I'm running on the latest version of PowerShell.