functions/public/Update-WebConfig.ps1

function Update-WebConfig {
    param (
        [Parameter(Mandatory = $true)]
        [string] $webConfigPath,
        [Parameter(Mandatory = $true)]
        [string] $settingKey,
        [string] $settingValue
    )

    if (!(Test-Path $webConfigPath)) {
        Write-DosMessage -Level Fatal -Message """$webConfigPath"" is not a valid path. Please specify a valid path to the apps web.config file"
    }

    $webConfigDoc = [xml](Get-Content $webConfigPath)
    if (!$webConfigDoc.configuration) {
        Write-DosMessage -Level Fatal -Message "This web.config file appears to not have a valid ""configuration"" xml node to write to"
    }
    
    if ($null -eq $webConfigDoc.configuration.appSettings) {
        $appSettings = $webConfigDoc.CreateElement("appSettings")
        $webConfigDoc.configuration.AppendChild($appSettings) | Out-Null
    }
    
    $appSettings = $webConfigDoc.configuration.SelectSingleNode('//appSettings')
    $existingSetting = $appSettings.add | Where-Object {$_.key -eq $settingKey}
    
    if ($null -eq $existingSetting) {
        $setting = $webConfigDoc.CreateElement("add")
    
        $keyAttribute = $webConfigDoc.CreateAttribute("key")
        $keyAttribute.Value = $settingKey;
        $setting.Attributes.Append($keyAttribute) | Out-Null
    
        $valueAttribute = $webConfigDoc.CreateAttribute("value")
        $valueAttribute.Value = $settingValue
        $setting.Attributes.Append($valueAttribute) | Out-Null
    
        $appSettings.AppendChild($setting) | Out-Null
    }
    else {
        $existingSetting.Value = $settingValue
    }
    
    $webConfigDoc.Save($webConfigPath)
}