PowerShell to Add Entry in Web.config AppSettings

SharePoint Web applications (or any web site built on ASP.NET) uses Web.config file to store and retrieve web site configurations such as database connection strings, security, etc. web.config file is actually a XML file with .config extension, typically located at the root of your web application.

At times, You may have to add/update web.config entries. we can automate changes to SharePoint web application’s web.config file using PowerShell. This PowerShell script gives you the ability to update web.config file.

PowerShell to Add entry in web.config’s AppSettings section

AppSettings section in web.config can be utilized to read/update configuration values for your SharePoint customization.

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue

#Config Parameters
$WebAppURL = "http://intranet.crescent.com"
$KeyName = "LicenseKey"
$KeyValue = "91e727402aa24e769e2779c155168e3"

#Get the web application
$WebApp = Get-SPWebApplication $WebAppURL

#Create new object for Web.config settings
$WebConfigModification = New-Object Microsoft.SharePoint.Administration.SPWebConfigModification
$WebConfigModification.Path = "configuration/appSettings"
$WebConfigModification.Name = "add[@key='$KeyName'][@value='$KeyValue']"
$WebConfigModification.Value = "<add key='$KeyName' value='$KeyValue' />"
$WebConfigModification.Sequence = 0
$WebConfigModification.Type = 0       
$WebConfigModification.Owner = "SharePointChartKey"
 
#Add "AppSettings" Entry to Web application's web.config
$WebApp.WebConfigModifications.add($WebConfigModification)
$WebApp.Update()
$WebApp.Parent.ApplyWebConfigModifications() 

This adds a new entry to the AppSettings section.

update web.config using powershell
Web.config changes doesn’t require server reboot!

Please note, web.config file changes are always subject to risky! They may get lost if you stop the “Microsoft SharePoint Foundation Web Application” service. As it’s machine-specific, you’ll have to repeat the changes in every WFE in a multi-server environment.

Salaudeen Rajack

Salaudeen Rajack is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

Leave a Reply