Update configSource of XML element in web.config u

2019-02-15 17:50发布

问题:

I am trying to figure out a way to update my web.config for different environments by updating the configSource for the appSettings element in the web.config.

Here are the way I know how to do it.

$xml.get_DocumentElement().appSettings.configSource = $replaced_test

The problem is that I want one base script where I can pass in different nodes to the script that I want to change and update but I am not sure how to do it.

For example, I want to be able to call a powershell script like this

changeWebConfig.ps1 nodeToChange newValueofNode

I hope this was clear enough.

This is the code I have now.

$webConfigPath = "C:\web.config"   

# Get the content of the config file and cast it to XML 
$xml = [xml](get-content $webConfigPath) 

#this was the trick I had been looking for  
$root = $xml.get_DocumentElement()."system.serviceModel".client.configSource  = $replace

# Save it  
$xml.Save($webConfigPath)

The problem I was having was the configuration node

I had to change it from

<configuration xmlns="http://schemas.microsoft.com/.NetConfiguration/v2.0">

this to

<configuration>

I am not sure how to find the node with the configuration node in it's orginal state yet, but I'm getting closer.

function Set-ConfigAppSetting
([string]$PathToConfig=$(throw 'Configuration file is required'),
         [string]$Key = $(throw 'No Key Specified'), 
         [string]$Value = $(throw 'No Value Specified'))
{
    if (Test-Path $PathToConfig)
    {
        $x = [xml] (type $PathToConfig)
        $node = $x.SelectSingleNode("//client[@configSource]")
        $node.configSource = $Value
        $x.Save($PathToConfig)
    }
} 

set-configappsetting "c:\web.config" CurrentTaxYear ".\private$\dinnernoworders" -confirm

回答1:

Finally figured it out.

$root = $xml.get_DocumentElement().SelectSingleNode("//client[@configSource]").configSource = "test"

of course, I will replace "//client[@configSource]" with a variable so I can pass in different nodes as parameters to create my base script.



回答2:

Im looking for a way to modify the code as well.

Here is a way you can view whats the node:

$path = 'c:\site\web.config'
$PublishState = (Select-Xml -Path $path -XPath "configuration/appSettings/add[@key='PublishState']/@value").Node.'#text'
$PublishState