Change XML from command line
I have an xml file with a structure as shown below and I would like to edit this file from the command line.
<server>
<service>
<Connector port="8080" password="password1234"/>
</service>
</server>
I would like to change the password or port number. Does cmd provide this option or do I need an additional tool? I know PowerShell can do this, but this is not the best solution for me. (Also, I didn't get it with powershell :(). It would also be okay to look for "password1234" and replace it because my file has a default password that is always the same and needs to be replaced.
source to share
To demonstrate one of the methods, I am using let, first create the xml file in your example:
Define variable for XML file name
$xmlFile = "C:\temp\myconfig.xml"
Define XML string to save to file
$xmlFromString = [xml]@"
<server>
<service>
<Connector port="8080" password="password1234"/>
</service>
</server>
"@
Save the xml content in a file
$xmlFromString.Save($xmlFile)
The resulting file
Get-Content -Path $xmlFile
<server>
<service>
<Connector port="8080" password="password1234" />
</service>
</server>
Here is PowerShell code to change values Get XML Content from File
$xml = [xml](Get-Content -Path $xmlFile)
Finds an element / Node and changes attribute values
$node = $xml.selectSingleNode('//server/service/Connector')
$node.port = "9090"
$node.password = "MyNewPassord4321"
Save XML Back content
$xml.Save($xmlFile)
results
Get-Content -Path $xmlFile
<server>
<service>
<Connector port="9090" password="MyNewPassord4321" />
</service>
</server>
Save the commands to a PowerShell ps1 file and execute / run it through PowerShell.
We'll need more information about what exactly you are trying to accomplish, for example:
- What rights will the user / account running the script have?
- Where will the script run? Local PC or Server?
- One or more servers / workstations?
- Performed by a Windows Scheduler Task?
Hope this was helpful. - Brooks
source to share