Assume you are trying to automate changes to one of your SharePoint web application’s web.config file using PowerShell. In order for you to be able to achieve this, you will need to instantiate a new object from the Microsoft.SharePoint.Administration namespace called SPWebConfigModification. This object will take in several properties such as the path to the key you are trying to modify, the name of your key, its value, the sequence in which it will appear in the parent node, as well as the name of the owner of that key.
As an example, assume we are trying to add a new AppSettings key name “MyContosoLicense” to store information about a license key for a third party we have installed in our farm. Our current web.config file looks like the following:
<?xml version=”1.0″ encoding=”utf-8″?>
<configuration>
[…]
<appSettings>
<add key=”Key1″ value=”Value1″ />
<add key=”Key2″ value=”Value2″ />
</appSettings>
[…]
</configuration>
Using the following PowerShell code, we will be able to insert our new “MyContosoLicense” key after the existing key.
$appSettingsModifications = New-Object Microsoft.SharePoint.Administration.SPWebConfigModification $appSettingsModifications.Path = "configuration/appSettings" $appSettingsModifications.Name = ''add[@key='MyContosoLicense'][@value='MyContosoValue']'' $appSettingsModifications.Value = ''<add key='MyContosoLicense' value='MyContosoValue' />'' $appSettingsModifications.Sequence = 0 $appSettingsModifications.Type = 0 $appSettingsModifications.Owner = "Admin"
Once you have created a web.config modification object using the lines of code above, you need to get a reference to the SharePoint Web Application on which you wish to make the changes. Remember that in the context of SharePoint, every web application gets its own web.config file.
$webApp = Get-SPWebApplication http://localhost $WebConfigModifications.Add($appSettingsModifications) $webApp.Update() $webApp.Parent.ApplyWebConfigModifications()
The resulting web.config node will be as follow:
<?xml version=”1.0″ encoding=”utf-8″?>
<configuration>
[…]
<appSettings>
<add key=”Key1″ value=”Value1″ />
<add key=”Key2″ value=”Value2″ />
<add key=”MyContosoLicense” value=”MyContosoValue” />
</appSettings>
[…]
</configuration>
Enjoy!