Reputation: 18147
I am trying to update node value using following powershell script
$XMLContents = [XML] (Get-content "C:\Test.xml")
$XPath="/Parameters/Parameter[ParameterName='pTxtRuntimeUserName']/ParameterValue"
$MachineNameInXML= Select-XML -XML $XMLContents -XPath $Xpath
$Userstring=$($MachineNameInXML.Node.'#text')
$Userstring = $Userstring.Replace("WIN2K8R25\administrator","WIN2K8R25\ABC")
$Userstring
$XMLContents.Save("C:\Test.xml")
When i display $Userstring , it displays the replaced value "WIN2K8R25\ABC" correctly but in xml file it was not updated. It is still the old username "WIN2K8R25\administrator".
My XML file is having many parameter node, I have copied some sample node values alone.
<Parameters>
<Parameter IsEncrypted="False">
<ParameterName>pTxtRuntimeUserName</ParameterName>
<ParameterValue>WIN2K8R25\administrator</ParameterValue>
</Parameter>
<Parameter IsEncrypted="False">
<ParameterName>pTxtABC</ParameterName>
<ParameterValue>XYCr</ParameterValue>
</Parameter>
</Parameters>
I am unable to find where do i miss. what am i missing in this ?
Upvotes: 0
Views: 4307
Reputation: 54881
Try:
$path = "C:\Test.xml"
$XMLContents = [XML] (Get-content $path)
$Node = $XMLContents.SelectNodes("/Parameters/Parameter[ParameterName='pTxtRuntimeUserName']/")
$Node[0].ParameterValue = $Node[0].ParameterValue.Replace("WIN2K8R25\administrator","WIN2K8R25\ABC")
$XMLContents.Save($path)
Might be a better looking way to do it, but as long as it's only one node with that paramtername it should work.
Upvotes: 1
Reputation: 101680
In this line:
$Userstring = $Userstring.Replace("WIN2K8R25\administrator","WIN2K8R25\ABC")
It looks like you're just reassigning the $Userstring
variable to a new value, but this has no effect on the contents of the DOM.
How about adding a new line after that:
$MachineNameInXML.Node.InnerText = $Userstring
Or you could skip using the $Userstring
variable altogether:
$XMLContents = [XML] (Get-content "C:\Test.xml")
$XPath="/Parameters/Parameter[ParameterName='pTxtRuntimeUserName']/ParameterValue"
$MachineNameInXML= Select-XML -XML $XMLContents -XPath $Xpath
$MachineNameInXML.Node.InnerText = $MachineNameInXML.Node.InnerText.Replace("WIN2K8R25\administrator","WIN2K8R25\ABC")
$XMLContents.Save("C:\Test.xml")
Upvotes: 2