Sets a web.config file's appSettings element key/value pair. If the element is not found, then a new one will created.

#
# Sets a web.config file's appSettings element
# key/value pair. If the element is not found, then a
# new one will created.
#

function Set-Webconfig-AppSettings
{
    param (
        # Physical path for the IIS Endpoint on the machine without the
        # "web.config" part.
        [parameter(mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String] $path,

        # Key to add/update
        [parameter(mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String] $key,

        # Value
        [parameter(mandatory = $true)]
        [ValidateNotNullOrEmpty()]
        [String] $value
    )

    Log ("Setting web.config appSettings for $path")

    $webconfig = Join-Path $path "web.config"
    [bool] $found = $false

    if (Test-Path $webconfig)
    {
        $xml = [xml](get-content $webconfig);
        $root = $xml.get_DocumentElement();

        foreach ($item in $root.appSettings.add)
        {
            if ($item.key -eq $key)
            {
                $item.value = $value;
                $found = $true;
            }
        }

        if (-not $found)
        {
            $newElement = $xml.CreateElement("add");
            $nameAtt1 = $xml.CreateAttribute("key")
            $nameAtt1.psbase.value = $key;
            $newElement.SetAttributeNode($nameAtt1);

            $nameAtt2 = $xml.CreateAttribute("value");
            $nameAtt2.psbase.value = $value;
            $newElement.SetAttributeNode($nameAtt2);

            $xml.configuration["appSettings"].AppendChild($newElement);
        }

        $xml.Save($webconfig)
    }
    else
    {
        Write-Error -Message "Error: File not found '$webconfig'"
    }
}