About Me

Having 12 years experience in Microsoft technologies.Since more than 7 years working in SharePoint technologies. Expert in providing consultation for SharePoint projects. Hands on with development and administration.

Monday 25 August 2014

Powershell Script - Modify Sharepoint web.config file entries

The following script will add/update SharePoint web.config file entries. The script accepts following input parameters. 

1. WebAppUrl - SharePoint web application url
2.WebConfigPath - Path for the SharePoint web application virtual directory

 Points to be noted
1. The following script backup existing web.config and add entries under configuration/appSettings & configuration/connectionStrings
 2. Provide input data in the form of .csv file with the separator as "$" with following header
 Configuration$Key$Value    
 Configuration is nothing but - the node where you want to add entries
3. The csv file should be in the same directory


Steps involved

1. Save following script as psUpdateSPWebApp.config.ps1


Param([Parameter(Mandatory=$true)]
      [String]
      $WebAppUrl,
      [Parameter(Mandatory=$true)]
      [String]
      $WebConfigPath
)

if ((gsnp Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue) -eq $null){
    asnp Microsoft.SharePoint.Powershell
}

$objShell = New-Object -Com Shell.Application
$folder = $objShell.BrowseForFolder(0,"Please select the folder containing your CSV file:",0)
$pathfld = $folder.Self.Path
$fullpath = Join-Path $pathfld "xxxxx.csv"

# Show Farm BuildVersion to ensure the SharePoint .net library is loaded
$localFarm = [Microsoft.SharePoint.Administration.SPFarm]::Local
$localFarm.BuildVersion

# store some settings and objects in variables
$webapp = [Microsoft.SharePoint.Administration.SPWebApplication]::Lookup($WebAppUrl)
$farmServices = @($webapp.Farm.Services | where-object { $_.TypeName -eq "Microsoft SharePoint Foundation Web Application" } )[0]


$currentDate = Get-Date -format MM-dd-yyyy-hh_mm_s # month-day-year - hours_mins_seconds
$backup = $WebConfigPath + "_$currentDate" + ".bak"

# Get the content of the config file and cast it to XML and save a backup copy labeled .bak followed by the date
$xml = [xml](get-content $WebConfigPath)
#save a backup copy
$xml.Save($backup)

$connectionStringsNode = $xml.SelectSingleNode("//configuration/connectionStrings")

        if ($connectionStringsNode -eq $null)
        {        
        Write-Host "connectionStrings node does not exist. Adding the node..." -ForegroundColor Cyan           
        # Node does not exist. So create it        
        $root = $xml.get_DocumentElement()                 
        $connectionStringsNode = $xml.CreateNode('element',"connectionStrings","")
        $configurationNode = $xml.configuration.AppendChild($connectionStringsNode)
        $connectionStringsNode = $xml.SelectSingleNode("//configuration/connectionStrings")
        $xml.Save($WebConfigPath)
        Write-Host "Successfully created connectionStrings node" -ForegroundColor Green           
        }

$appSettingsNode = $xml.SelectSingleNode("//configuration/appSettings")

        if ($appSettingsNode -eq $null)
        {        
        Write-Host "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","")
        $configurationNode1 = $xml.configuration.AppendChild($appSettingsNode)
        $appSettingsNode = $xml.SelectSingleNode("//configuration/appSettings")
        $xml.Save($WebConfigPath)
        Write-Host "Successfully created appSettings node:" -ForegroundColor Green
        }

Import-Csv -Delimiter "$" -Path $fullpath | % {

if($_.Configuration -eq "appSettings")
{
    $appSettings = New-Object Microsoft.SharePoint.Administration.SPWebConfigModification
    $appSettings.Path = “/configuration/appSettings”;

    $appSettings.Name = [system.string]::format(“add[@key=""{0}""]“, $_.Key);
    $appSettings.Value = [system.string]::format(“<add key=”"{0}”" value=”"{1}”" />”, $_.Key, $_.Value);

   
    $appSettings.Sequence = 0
    $appSettings.Owner = “SharePoint”
    $appSettings.Type = 0

    $webapp = Get-SPWebApplication $WebAppUrl
    $webapp.WebConfigModifications.Add($appSettings)
    $webapp.Update()
    #$webapp.Parent.ApplyWebConfigModifications()
    $farmServices.ApplyWebConfigModifications()
    Write-Host "Successfully created appSettings key:" $_.Key -ForegroundColor Green
}

elseif($_.Configuration -eq "connectionStrings")
{
    $value = $_.Value
    $connectionString = New-Object "Microsoft.SharePoint.Administration.SPWebConfigModification"
    $connectionString.Path = "configuration/connectionStrings"
    $connectionString.Name = "ECConnectionString"
    $connectionString.Sequence = 0 
    $connectionString.Type = 0 
    $connectionString.Owner = "ECConnectionStringOwner"
    $connectionString.Value = $value
    $webapp.WebConfigModifications.Add($connectionString)  #Update the Web Application and apply all existing web.config modifications 
    $webapp.Update() 
    #$webapp.Parent.ApplyWebConfigModifications()
    $farmServices.ApplyWebConfigModifications()
    Write-Host "Successfully created connectionStrings key:" $_.Key -ForegroundColor Green
}

}# end of second import


Step2: Create batch file to run the script. Save file in .bat format.
cd /d %~dp0
powershell -file ./psUpdateSPWebApp.config.ps1 -WebAppUrl "xxxxx" -WebConfigPath "C:\inetpub\wwwroot\wss\VirtualDirectories\443\web.config"
pause
 

Happy powershell coding... please feel free to comment...

No comments:

Post a Comment