I am trying to replace DeviceAddress value in a XML file and save it as a new file, but not getting the desired result.
XML File:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<WinCollectConfiguration version="7.3.0.41" xmlns="event_collection/WinCollect">
<Service version="7.3.0.41" classification="Service" type="Service" module="Win" name="DestinationManager">
<InstanceData>
<Instance name="Software">
<Environment />
<Module order="1" service_name="StoreAndForwardStage">
<Environment>
<Parameter name="DataChunkPeriod" value="10" />
<Parameter name="DataProcessingPeriod" value="500000" />
</Environment>
</Module>
<Module order="2" service_name="SimpleEventThrottle">
<Environment>
<Parameter name="EventThrottleInEPS" value="5000" />
</Environment>
</Module>
<Module order="3" service_name="SyslogHeaderStage">
<Environment />
</Module>
<Module order="4" service_name="TCPSendStage">
<Environment>
<Parameter name="TargetAddress" value="0.0.0.0" />
<Parameter name="TargetPort" value="80" />
<Parameter name="Secondary" value="" />
<Parameter name="Failover" value="" />
</Environment>
</Module>
</Instance>
</InstanceData>
<Environment />
</Service>
<Service version="7.3.0.41" classification="Service" type="DeviceType" module="DeviceWindowsLog" name="DeviceWindowsLog">
<InstanceData>
<Instance enabled="true" name="SERVER">
<Environment>
<Parameter name="DeviceAddress" value="SERVER" />
<Parameter name="RemoteMachine" value="SERVER" />
</Environment>
</Instance>
</InstanceData>
<Environment>
<Parameter name="AdaptiveThreadPool.ReaderThreadsMin" value="5" />
</Environment>
</Service>
</WinCollectConfiguration>
Powershell Script
$xmldata = [XML](Get-Content -raw 'C:\Pester\config.xml')
$tochange = "DeviceAddress"
foreach ($add in $xmldata.WinCollectConfiguration.Service.InstanceData.Instance.Environment.Parameter)
{
$add
if ($tochange -contains $add.name)
{
$add.value = "192.168.0.1"
}
$add
}
The above code adds a new line instead of replacing. I also tried with replace function it gives me a different result.
name value
---- -----
DeviceAddress SERVER
DeviceAddress 192.168.0.1
RemoteMachine SERVER
RemoteMachine SERVER
CodePudding user response:
One way to do it, is to use SelectSingleNode()
:
$expression = "//*[local-name()='Parameter'][./@name='$tochange']";
$target = $xmldata.SelectSingleNode($expression);
$target.InnerText="192.168.0.1";