使用PowerShell在config/xml文件中查找密钥并替换其各自的值



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

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

那么它的作用是用Newvalue字符串替换所有的Value1字符串。我在这里面临的问题是,它改变了所有找到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

不要对结构化标记使用正则表达式-使用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节点,该节点具有值为key1的名为key的属性,并且其父节点是appSettings节点。

最新更新