-2

I'm trying to add some new settings to a tomcat server.xml file datasource. I can match the last setting in the datasource, which has a password that I need to capture, but when I try to replace it, I'm not see any changes.

$serverXml = "C:\server.xml"
$xml = Get-Content $serverXml
$password = (($xml -match "                  password=""(.*)""").Replace('                  password="', "").Replace('"  />', ''))[0]
$oldString = @"
              username="cf.user"
              password="$password"  />
"@
$newString = @"
              username="cf.user"
              password="$password"
              testWhileIdle="true"
              testOnBorrow="true"
              testOnReturn="false"
              validationQuery="select 1"
              validationInterval="30000"
              minEvictableIdleTimeMillis="30000"  />
"@
$xml = $xml.replace($oldString, $newString)
Set-Content -Path $serverXml -Value $xml

I'm able to match the $password fine, but when I'm using it as a variable to pass into $oldString and $newString in the replace, its not matching anymore. Even $xml -match $oldString doesn't return anything, but totally should as far as I can tell.

  • 2
    I see `xml` but you never cast a variable [xml] or treat it as such - handling xml data as text complicates things. See [this Q&A](https://stackoverflow.com/questions/18032147/parsing-xml-using-powershell) –  May 01 '18 at 20:54

1 Answers1

3

Do not edit XML via string replacements. Use the gratuitous XML parser PowerShell provides you with.

Load the config file like this:

[xml]$xml = Get-Content $serverXml

or like this:

$xml = New-Object Xml.XmlDocument
$xml.Load($serverXml)

The latter is a bit more failsafe, because it will (for instance) check that the encoding of the file actually matches the encoding specified in the preamble.

Select nodes via XPath expressions:

$node = $xml.SelectSingleNode('/Path/To/Node')

Change existing attributes like this:

$node.Attributes['password'] = 'newpassword'

Add new attributes like this:

$attr = $xml.CreateAttribute('testWhileIdle')
$attr.Value = 'true'
[void]$node.Attributes.Append($attr)

Then save the modified XML back to the file:

$xml.Save($serverXml)
Ansgar Wiechers
  • 193,178
  • 25
  • 254
  • 328