找到该密钥并使用powershell

时间:2018-11-20 04:53:43

标签: xml powershell app-config powershell-v1.0

我有一个类似于以下的配置文件:

<?xml version="1.0" encoding="utf-8"?>
<configuration>  
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
  </startup>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="System.Net.Http" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-4.1.1.3" newVersion="4.1.1.3" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
        <bindingRedirect oldVersion="0.0.0.0-11.0.0.0" newVersion="11.0.0.0" />
      </dependentAssembly>      
    </assemblyBinding>
  </runtime>
  <appSettings>
    <add key="key1" value="Value1" />
    <add key="key2" value="Value12" />
    <add key="key3" value="Value3" />   
  </appSettings>
</configuration>

现在通过Powershell,我正在尝试替换一些值,例如Value1。为此,我编写了以下脚本:

$original_file = "C:\test.xml"
(Get-Content $original_file) | Foreach-Object {
     $_ -replace 'Value1', 'Newvalue'
    } | Set-Content $original_file

那么它将用Value1字符串替换所有Newvalue字符串。我在这里面临的问题是,更改Value1所在的所有值,就像这样。

  <appSettings>
    <add key="key1" value="Newvalue" />
    <add key="key2" value="Newvalue2" /> --- this is not supposed to happen
    <add key="key3" value="Value3" />  
</appSettings>

实际上,我的实际值是很长的字符串。

那么我有什么办法可以找到密钥并更改其各自的值?类似于查找Key1,并将其值更改为NewValue

我们非常感谢您的帮助。

1 个答案:

答案 0 :(得分:1)

Don't use regex against structured markup-使用XPath!

# Load the xml document
$filename = 'C:\test.xml'
$xmlDoc = New-Object xml
$xmlDoc.Load($filename)

# Select all applicable nodes
$nodes = $xmlDoc.SelectNodes('//appSettings/add[@key="key1"]')

# In each node, replace the value `Value1` with `NewValue`
foreach($node in $nodes){
  $node.value = $node.value.Replace('Value1','NewValue')
}

# Save the document
$xmlDoc.Save($filename)

XPath表达式//appSettings/add[@key="key1"]将选择具有属性add且其值为key且其父节点为key1的任何appSettings节点。