Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modify XML from the command line

I have a xml-file with a structure as following 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 the port-number.

Does cmd provide this option or do I need an extra tool? I know PowerShell can do it but that's not the best solution for me. (Besides I didn't get it run with powershell :( ).

It would be also ok to search for "password1234" and replace it, because there is a default password in my file which is always the same and this must be replaced.

like image 208
Tobi123 Avatar asked Jul 06 '15 10:07

Tobi123


1 Answers

To demonstrate one method I use let first create the xml file in your example:

Define a Variable for the XML Filename

$xmlFile = "C:\temp\myconfig.xml"

Define an XML String to save to the file

$xmlFromString = [xml]@"
<server>
<service>
<Connector port="8080" password="password1234"/>
</service>
</server>
"@

Save the xml contents to the file

$xmlFromString.Save($xmlFile)

Resulting file content

Get-Content -Path $xmlFile
<server>
  <service>
    <Connector port="8080" password="password1234" />
  </service>
</server>

Here is the PowerShell code to change the values Get XML content from file

$xml = [xml](Get-Content -Path $xmlFile)

Finds the Element / Node and change the attribute values

$node = $xml.selectSingleNode('//server/service/Connector')
$node.port = "9090"
$node.password = "MyNewPassord4321"

Save the XML Contents Back out

$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 via PowerShell.

We'll need additional details on what exactly your trying to accomplish such as:

  • What rights will the user / account running the script has?
  • Where will the script be running from? Local PC or server?
  • One or multiple servers/work stations?
  • Executed via Windows Scheduler Task?

Hope that was helpful. - Brooks

like image 76
Brooks Avatar answered Oct 24 '22 17:10

Brooks