I have an config file similar to below:
<?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>
Now through PowerShell I'm trying to replace some values, say for example Value1
. For that I have written the below script :
$original_file = "C:\test.xml"
(Get-Content $original_file) | Foreach-Object {
$_ -replace 'Value1', 'Newvalue'
} | Set-Content $original_file
So what it does it replace all Value1
strings with Newvalue
string. The problem I'm facing here is it changing all the values whereever Value1
is found, like this.
<appSettings>
<add key="key1" value="Newvalue" />
<add key="key2" value="Newvalue2" /> --- this is not supposed to happen
<add key="key3" value="Value3" />
</appSettings>
And also in reality, I actual values are very long strings.
So is there any way I can find the key and change its respective value? Like find Key1
and change its value to NewValue
.