Removing web.config modifications using Powershell

In many custom SharePoint solutions the SPWebConfigModification class is often used to persist changes to the web.config file for a given web application in the farm. This is a very good way to keep track of your changes to the web.config file through feature activation on a web application level.

But sometimes you’ll need to remove an entry in a web.config file for a given web application. This could be a safecontrol, an AppSetting or a ConnectionString. It is generally not a good idea to remove this manually, since inconsistency between the web.config file and the content database will occur and that is not good.

Powershell can help you remove an entry in the web.config file properly. See the following example:

$webApp = Get-SPWebApplication "http://yoursite"
$config = $webApp.WebConfigModifications | Where-Object {$_.Name -eq "add[@name=['Session']" -and $_.Path -eq "configuration/system.web/httpModules"}
$webApp.WebConfigModifications.Remove($config)
$webApp.Update()
$webApp.Parent.ApplyWebConfigModifications()

The example above will remove the modification with the name add[@name=[‘Session’] and path configuration/system.web/httpModules. The ApplyWebConfigModifications() function which is called at the end of the script will apply the changes to the web.config file across the farm.