【问题标题】:Using variables inside PowerShell replace在 PowerShell 中使用变量替换
【发布时间】:2018-10-11 21:30:11
【问题描述】:

我正在尝试向 tomcat server.xml 文件数据源添加一些新设置。我可以匹配数据源中的最后一个设置,它有一个我需要捕获的密码,但是当我尝试替换它时,我看不到任何更改。

$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

我可以很好地匹配 $password,但是当我使用它作为变量传递到替换中的 $oldString 和 $newString 时,它不再匹配。即使$xml -match $oldString 也没有返回任何东西,但据我所知完全应该。

【问题讨论】:

  • 我看到了xml,但您从不强制转换变量 [xml] 或将其视为 - 将 xml 数据作为文本处理会使事情复杂化。见this Q&A

标签: powershell


【解决方案1】:

Do not edit XML via string replacements。使用 PowerShell 为您提供的免费 XML 解析器。

像这样加载配置文件:

[xml]$xml = Get-Content $serverXml

或者像这样:

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

后者更安全一些,因为它会(例如)检查文件的编码是否与序言中指定的编码实际匹配。

通过XPath expressions选择节点:

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

像这样更改现有属性:

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

像这样添加新属性:

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

然后将修改后的 XML 保存回文件:

$xml.Save($serverXml)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-24
    • 2020-08-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多