Powershell script to update XML file content Powershell script to update XML file content powershell powershell

Powershell script to update XML file content


I know this is an old post but this may help others so...

If you specifically know the elements that you are looking for then you can simply specify the element like so:

# Read the existing file[xml]$xmlDoc = Get-Content $xmlFileName# If it was one specific element you can just do like so:$xmlDoc.config.button.command = "C:\Prog32\folder\test.jar"# however this wont work since there are multiple elements# Since there are multiple elements that need to be # changed use a foreach loopforeach ($element in $xmlDoc.config.button){    $element.command = "C:\Prog32\folder\test.jar"}    # Then you can save that back to the xml file$xmlDoc.Save("c:\savelocation.xml")


You have two solutions. You could read it as xml and replace the text, like this:

#using xml$xml = [xml](Get-Content .\test.xml)$xml.SelectNodes("//command") | % {     $_."#text" = $_."#text".Replace("C:\Prog\Laun.jar", "C:\Prog32\folder\test.jar")     }$xml.Save("C:\Users\graimer\Desktop\test.xml")

Or you could do the same much simpler and faster using simple string-replacement like if it was a normal text-file. I would recommend this. Ex:

#using simple text replacement$con = Get-Content .\test.xml$con | % { $_.Replace("C:\Prog\Laun.jar", "C:\Prog32\folder\test.jar") } | Set-Content .\test.xml


Try this:

$xmlFileName = "c:\so.xml"$match = "C:\\Prog\\Laun\.jar"$replace = "C:\Prog32\folder\test.jar"# Create a XML document[xml]$xmlDoc = New-Object system.Xml.XmlDocument# Read the existing file[xml]$xmlDoc = Get-Content $xmlFileName$buttons = $xmlDoc.config.button$buttons | % {     "Processing: " + $_.name + " : " + $_.command    $_.command = $_.command -Replace $match, $replace    "Now: " + $_.command    }"Complete, saving"$xmlDoc.Save($xmlFileName)