Search code examples
xmlpowershellpowershell-4.0

Powershell to update xml not working as expected


I have a xml snippet like the one below:

<userSettings>
  <setting name="DataLimit">500</setting>
  <setting name="ChunkSize">7000</setting>
  <setting name="RequestFormat">rawXML</setting>

I want to update the xml cell value of ChunkSize from 7000 to 500000 and have the following script which I picked up from Stack Overflow:

$xml = [xml](Get-Content "C:\Users\ldap_user\AppData\Local\Office Connection\OfficeReportingSettings.xml")
$xml.SelectNodes("//ChunkSize") | % { 
    $_."#text" = $_."#text".Replace("7000", "5000000") 
    }

$xml.Save("C:\Users\ldap_user\AppData\Local\Office Connection\OfficeReportingSettings.xml")

The script doesn't error out and I see the .xml file timestamp changed to current time. However the value still stays 7000. Please let me know what am I missing. Also I want to run this against the same .xml file residing in hundreds of user profile on the same terminal server. BTW I am running this script on a Windows 2016 server and the version of Powershell is:

(Get-Host).Version

Major  Minor  Build  Revision
-----  -----  -----  --------
5      1      14393  3383    

Thanks a lot in advance


Solution

  • You are having issues with saving your updated content because you are not actually making any changes to the content. Your node selection syntax must change so that you are actually selecting an applicable element and attribute.

    $xml.SelectNodes("//setting[@name='ChunkSize']") | Foreach-Object { 
        $_.'#text' = $_.'#text'.Replace('7000','5000000') 
    }
    

    The XPath syntax breaks down to //element and [@attribute='value']. setting is the element. name is the attribute. ChunkSize is the attribute value. Keep in mind that XPath queries are case sensitive.