-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.

1
  • 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 Commented May 1, 2018 at 20:54

1 Answer 1

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)
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.