Friday, August 29, 2014

Update Web Config through PowerShell

Hi,

There was a requirement of updating our timer job config with the below values in app settings section.
Post that we are picking the values from our web part.

<add key="NucleusSiteURL" value="https://oabc.com/sites/Nucleus" />
    <add key="NucleusSalesWorkShopLibrary" value="SalesWorkShop" />
    <add key="NucleusWikiSiteURL" value="https://oabc.com/sites/Nucleus/WikiSite" />
    <add key="NucleusPagesLibrary" value="Pages" />
    <add key="NucleusRFIRFPFAQ" value="RFI / RFP FAQs" />

Now for these entries we had created the below PowerShell script

if ((Get-PSSnapin -Name Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null )
{
            Add-PSSnapin Microsoft.SharePoint.Powershell
}
Write-Host "Entered???"
$WebAppConfigPath = "C:\inetpub\wwwroot\wss\VirtualDirectories\80\web.config"
Write-Host "Loading Web.Config as XML in " $WebAppConfigPath -ForegroundColor Cyan
[xml]$xml = Get-Content $WebAppConfigPath
Write-Host "Started" -ForegroundColor Green
$appSettingNode =$xml.SelectSingleNode("//configuration/appSettings")
if ($appSettingNode -eq $null)
    {
    Write-Host "Inside if loop" -ForegroundColor Green
                $addAppsettingNode=$xml.CreateNode('element',"appSettings","")
    $appSettingNode=$xml.SelectSingleNode("//configuration").AppendChild($addAppsettingNode)
    #$addAppsettingNode=$xml.SelectSingleNode("//configuration").AppendChild($addAppsetting)
    }
    else
    {
     Write-Host "Inside else loop" -ForegroundColor Green
    #$appSettingNode=$xml.SelectSingleNode("//configuration/appSettings").AppendChild($addAppsetting)
    }


$config1=$xml.CreateNode('element',"add","")
$config1.SetAttribute('key','NucleusSiteURL')
$config1.SetAttribute('value','https://oabc.com/sites/Nucleus')

$config2=$xml.CreateNode('element',"add","")
$config2.SetAttribute('key','NucleusSalesWorkShopLibrary')
$config2.SetAttribute('value','SalesWorkShop')

$config3=$xml.CreateNode('element',"add","")
$config3.SetAttribute('key','NucleusWikiSiteURL')
$config3.SetAttribute('value','https://oabc.com/sites/Nucleus/WikiSite')

$config4=$xml.CreateNode('element',"add","")
$config4.SetAttribute('key','NucleusPagesLibrary')
$config4.SetAttribute('value','Pages')

$config5=$xml.CreateNode('element',"add","")
$config5.SetAttribute('key','NucleusRFIRFPFAQ')
$config5.SetAttribute('value','RFI / RFP FAQs')

$appSettingNode.AppendChild($config1)
$appSettingNode.AppendChild($config2)
$appSettingNode.AppendChild($config3)
$appSettingNode.AppendChild($config4)
$appSettingNode.AppendChild($config5)

$xml.Save($WebAppConfigPath)
Write-Host "Completed" -ForegroundColor Green
Finally it is inserting the values as below

No comments:

Post a Comment