SharePoint 2010 Cookbook: How to Remove a web.config Modification Using PowerShell

Some custom SharePoint products make changes to the web.config of a Web application via SPWebConfigModification objects to support their features. Sometimes, we need to remove these changes for a particular Web application (usually because the custom product is never used on this Web application). Still, manually removing the text is not a good idea because the web.config would not match what has been set in the configuration database and might cause problems. In this article, I will demonstrate how to properly remove these web.config settings using PowerShell.

Challenge:

How can I remove a web.config modification properly using PowerShell?

Solutions:

First, open SharePoint 2010 Management Shell. From the Start menu, select All Programs > Microsoft SharePoint 2010 Products > SharePoint 2010 Management Shell:

Next, list all of the SPWebConfigModification objects that have been applied to the Web application. These objects are stored in the WebConfigModifications property of the Web application. In this example, you can see some of the modifications added Bamboo products to support Telerik:

   1: $webApp = Get-SPWebApplication WebApplicationURL
   2: $webApp.WebConfigModifications

Now, we can identify a particular modification and remove it using the below commands. In this example, I’ll try to remove the modification with name “add[@name=[‘Session’]” and path “configuration/system.web/httpModules”:

   1: $config = $webApp.WebConfigModifications | Where-Object {condition_to_identify_the_object}
   2: $webApp.WebConfigModifications.Remove($config)
   3: $webApp.Update()
   4: $webApp.Parent.ApplyWebConfigModifications()

The ApplyWebConfigModifications() method applies this change across the farm, so we don’t need to worry about each physical web.config file at the server-level. That is one of the main advantages of using PowerShell to update web.config modifications.

If there are multiple modifications we need to remove, we can use a loop to do that. The following example removes all of the modifications added to Bamboo Telerik Config in a particular Web application (they all have the same Owner value):

   1: $BambooConfigs  = $webApp.WebConfigModifications | Where-Object {$_.Owner -eq "Bamboo.SP2010.Config"}
   2: foreach ($config in $BambooConfigs) {
   3:     $webApp.WebConfigModifications.Remove($config)
   4: }
   5: $webApp.Update()
   6: $webApp.Parent.ApplyWebConfigModifications()

Discussion:

  • The commands in this article work with both SharePoint 2010 Foundation and Server.
  • Be extra careful when making changes to the web.config. Do not remove a modification unless you are sure what it is.

See Also:

  • SharePoint 2010 Cookbook: How to Add a web.config Modification Using PowerShell