Stefan Szasz
Stefan Szasz

Reputation: 1256

Replace app.config item node value in powershell

Having the following app.config:

<configuration>
<appSettings>
 <add key="filepath" value="D:\Data" />
 <add key="node2" value="..." />
 ...
</appSettings>
</configuration>

I want to replace the setting that has 'filepath' key with a new value (by replacing 'D:\Data..' in this case). The new value should be passed as a parameter to the powershell script. Thanks

Upvotes: 5

Views: 5697

Answers (1)

ravikanth
ravikanth

Reputation: 25810

Update based on the comment:

$xml = [xml]'<configuration>
<appSettings>
 <add key="filepath" value="D:\Data" />
 <add key="filename" value="test.log" />
</appSettings>
</configuration>'

$xml.configuration.appSettings.add | foreach { if ($_.key -eq 'filepath') { $_.value = "C:\Data" } }
$xml.Save("C:\dell\NewApp.config")

===========================================================================================

OLD ANSWER

$xml = [xml]'<configuration>
<appSettings>
 <add key="filepath" value="D:\Data" />
</appSettings>
</configuration>'

$xml.configuration.appSettings.add.value = "C:\Data"
$xml.Save("NewApp.config")

or

$xml = [xml](Get-Content App.config)
$xml.configuration.appSettings.add.value = "C:\Data"
$xml.Save("NewApp.Config")

Upvotes: 6

Related Questions