Powershell script to update XML file content

前端 未结 3 1564
天涯浪人
天涯浪人 2020-12-15 16:25

Please help me create a Powershell script that will go through an XML file and update content. In the example below, I want to use the script to pull out and change the fil

相关标签:
3条回答
  • 2020-12-15 17:02

    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 loop
    foreach ($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")
    
    0 讨论(0)
  • 2020-12-15 17:05

    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
    
    0 讨论(0)
  • 2020-12-15 17:06

    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)
    
    0 讨论(0)
提交回复
热议问题