Thursday, February 7, 2013

PowerShell : Updating appSettings section in web.config


I was required to update the appSettings with some elements in web.config of a SharePoint web application. Here is the code to update it using PowerShell. This code checks if appSettings section. If its not there, it will be created. Then it checks if serviceURL node is there. If it is found, it deletes and recreates with updated value. Note: Some variables need to be updated before executing the code.
 
Function Update-AppSettingsSection {
    Write-Host "Updating AppSettings section..." -foregroundcolor "Cyan"
    
    # Prepare variables required to extract Web.Config from SPWebApplication
    SetupEnvironment

    # Get the path to the config file from $WebApp
    $WebAppZone = $WebApp.AlternateUrls[0].UrlZone
    $IISSettings = $WebApp.IisSettings[$WebAppZone]
    $WebAppConfigPath = $IISSettings.Path.ToString() + "\Web.Config"
    
    Write-Host -NoNewline "(Update-AppSettingsSection)Loading Web.Config as XML in "$WebAppConfigPath"...." -ForegroundColor Cyan
    [xml]$xml = Get-Content $WebAppConfigPath
    Write-Host "Done" -ForegroundColor Green

    # Check if appSettings node exists
    $appSettingsNode = $xml.SelectSingleNode("//configuration/appSettings")
    if ($appSettingsNode -eq $null)
    {
        Write-Host -NoNewline "appSettings node does not exist. Adding the node..." -ForegroundColor Cyan

         # Node does not exist. So create it
        $root = $xml.get_DocumentElement();         
        $appSettingsNode = $xml.CreateNode('element',"appSettings","")    
        $configurationNode = $xml.configuration.AppendChild($appSettingsNode)
        $appSettingsNode = $xml.SelectSingleNode("//configuration/appSettings")
        
        #Apply to Web.Config
        $xml.Save($WebAppConfigPath)
        Write-Host "Done." -ForegroundColor Green
    }

     # Check for serviceURL
    $serviceURLNode = $xml.SelectSingleNode("//configuration/appSettings/add[@key='serviceURL']")
    if ($serviceURLNode -ne $null)
    {
        Write-Host -NoNewline serviceURL entry found in Web.Config...." -ForegroundColor Cyan
        # Delete the entry to recreate and update
        $temp = $appSettingsNode.RemoveChild($serviceURLNode)
        Write-Host -NoNewline "Node removed." -ForegroundColor Cyan
    }

    # Recreate the servieURL node
    $root = $xml.get_DocumentElement();         
    $serviceURLNode = $xml.CreateNode('element',"add","")    
    $serviceURLNode.SetAttribute("key", "serviceURL")
    $serviceURLNode.SetAttribute("value", $serviceURL )
    $appSettingsNode =  $xml.SelectSingleNode("//configuration/appSettings").AppendChild($serviceURLNode)

    #Apply to Web.Config
    $xml.Save($WebAppConfigPath)
    Write-Host "Done." -ForegroundColor Green
    
    Write-Host "appSettings section updated successfully." -foregroundcolor "Green"
}

No comments:

Post a Comment