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 an XML file with .config extension, typically located at the root of your web application.

You may have to add/update web.config entries at times. We can automate changes to the SharePoint web application’s web.config file using PowerShell. This PowerShell script gives you the ability to update the 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 = "https://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

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 risk! 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 multiserver environment.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. Passionate about sharing the deep technical knowledge and experience to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *