Creating a Powershell script to add a key to multiple web.config files.

by May 22, 2013

I am attempting to create a script that will update multiple web config files (120) with a new add key value. So far the script is what I have so far, however when I run it. It adds it as a hole new node instead of just an add key value. Please help! 

 

********************Web.config**********************

  <appSettings>

 

    <add key="Database" value="something" />

    <add key="UUDecodePassword" value="true" />

    <!–<add key="ClientName" value="DEVELOPMENT" />–>

    <add key="ClientFolder" value="Test" />

    <add key="OfflineApplicationHref" value="https://snowboaridng.com/publish.htm" />

    <!–<add key="ReportingServiceHref" value="https://snowboaridng.com/report/publish.htm" />–>

    <!–<add key="ReportingServiceUserName" value="" />–>

    <!–<add key="ReportingServicePassword" value="" />–>

    <!–<add key="ReportingServiceDomain" value="" />–>

    <add key="ReportViewerServerConnection" value="ReportViewerServerConnection, APP_CODE" />

    <!–<add key="WebDialerURL" value="https://snowbaording.com/rider/services/rider/SoapService"/>–>

    <add key="CacheHost" value="testdb" />

    <add key="aspnet:MaxHttpCollectionKeys" value="5000" />

      <add key="https://snowboaridng.com/admin/AuthForm.aspx?guid=5265df71-1fb2-4436-ac94-bf4cde170005" />

  </appSettings>

 

*************************************************************

 

*********************Begin Script ******************************

 

# Array of files to make changes to, add as many as you like

$filesarray = @("C:UsersDocumentspowershellscriptwebconfigwebsn.config","C:UsersDocumentspowershellscriptwebconfigwebsb.config") 

# Go thru all files

foreach ($filename in $filesarray)

{

    # Get file + cast as xml

    $xml = [xml](get-content $filename)

 

    # Backup file before making changes

    $backup = $filename + "-" + (get-date).tostring("yyyy-MM-dd-hh_mm_s")

    $xml.Save($backup)

 

    $root = $xml.get_DocumentElement();

 

 # Add a new node

    $node = $xml.createElement("FeedbackFormURL")

    $root."appSettings".appendChild($node)

    $subnode = $xml.createElement("add")

    $node.AppendChild($subnode)

    $attribute = $xml.CreateAttribute("key")

    $attribute.set_Value("https://snowboaridng.com/admin/AuthForm.aspx?guid=5265df71-1fb2-4436-ac94-bf4cde170005")

    $subnode.SetAttributeNode($attribute )

 

    # Save

    $xml.Save($filename)     

}