Wednesday, November 20, 2013

Enable Session State Script

Hi,

Earlier we were updating below details in web config manually
Now as part of migration from Sharepoint 2010 to Sharepoint 2013 we had automate the above through power shell as below

// EnableSessionState_Batch.bat
Powershell.exe -Command Set-ExecutionPolicy "Bypass"
Powershell.exe -Command "& {E:\Naga\EnableSessionState\EnableSessionState.ps1}"
Pause

// EnableSessionState.xml
<?xml version="1.0" encoding="utf-8" ?>
<SessionInputs>
<WebAppConfigPath>C:\inetpub\wwwroot\wss\VirtualDirectories\32113\web.config</WebAppConfigPath>
</SessionInputs>

// EnableSessionState.ps1
#-----Input parameters to the script
$snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
if ($snapin -eq $null)
{
Write-Host "Loading SharePoint Powershell Snap-in"
Add-PSSnapin "Microsoft.SharePoint.Powershell"
}

# Get complete file path (eg:  E:\SP2010\xxxx.ps1)
$filepath = $MyInvocation.MyCommand.Definition                                       
# Get current Directory  file path  (eg:  E:\SP2010)
$directorypath = [System.IO.Path]::GetDirectoryName($filepath)        
# Get current Drive   (eg:  E:\)
$directory = Get-Item $directorypath | Split-Path -Parent             
$InputFile = $directorypath+"\EnableSessionState.xml"

$xmlinput = [xml] (get-content $InputFile)
$item = $xmlinput.SessionInputs

## Start logging
$LogTime = Get-Date -Format yyyy-MM-dd_h-mm
$LogFile = $directorypath + "\EnableSessionState-$LogTime.rtf"
Start-Transcript -Path $LogFile -Force

#---------------------Variables-----------------------------------#
#$csvfpath - to get csv file path from xml
$wappconfigpath = $item.WebAppConfigPath
#-----------------------------------------------------------------#

#-----------Function to add Session State----------------------------------------------------------#
try
{
Function AddSessionState {
    Write-Host "Enabling Sessions for SharePoint Web Application..." -foregroundcolor "Cyan"

    # Get the path to the config file from $WebApp
    # Prepare variables required to extract Web.Config from SPWebApplication   

    ##$WebAppConfigPath = "C:\inetpub\wwwroot\wss\VirtualDirectories\42275\Web.Config"
   
    Write-Host "Loading Web.Config as XML in " $WebAppConfigPath -ForegroundColor Cyan
    [xml]$xml = Get-Content $wappconfigpath
    Write-Host "Done" -ForegroundColor Green  
  
    # Check for system.webserver node
    $moduelsNode = $xml.SelectSingleNode("//configuration/system.webServer/modules")
    if ($moduelsNode -ne $null)
    {
        Write-Host "modules node exists in  section. Updating the node..." -ForegroundColor Cyan    

        # Check for
        $addSessionNode = $xml.SelectSingleNode("//configuration/system.webServer/modules/add[@name='Session']")
        if ($addSessionNode -ne $null)
        {
            Write-Host "'' entry found in Web.Config....So no updates made for this node." -ForegroundColor Cyan
        }
        else
        {
            # Recreate the  node
            $root = $xml.get_DocumentElement();        
            $addSessionNode = $xml.CreateNode('element',"add","")   
            $addSessionNode.SetAttribute("name", "Session")
            $addSessionNode.SetAttribute("type", "System.Web.SessionState.SessionStateModule")
            $appSettingsNode =  $xml.SelectSingleNode("//configuration/system.webServer/modules").AppendChild($addSessionNode)

            #Apply to Web.Config
            $xml.Save($wappconfigpath)

            Write-Host -NoNewline "'' entry created in Web.Config." -ForegroundColor Green
        }
    }

    Write-Host "Sessions enabled successfully." -foregroundcolor "Green"
} AddSessionState
#-----------------------------------------------------------------------------------------------------------------#
#-----------Function to Enable Session State----------------------------------------------------------------------#
function Set-enableSessionState{
    param([string]$path = $(read-host "Please enter a web.config file to read"),
          [string]$value = $(read-host "Set Session State : 'true' or 'false'"))   
    
    $date = (Get-Date).tostring("mm_dd_yyyy-hh_mm_s");
    $backup = $path + "_$date";
    $xml = [xml](Get-Content $path);

    $xml.Save($backup);
    $root = $xml.get_documentElement();
    $sysweb = $root["system.web"];
    $sysweb.pages.SetAttribute("enableSessionState",$value);
   
    $xml.Save($path);   
}

Set-enableSessionState $wappconfigpath "true"
Write-Host "Session State has been enabled..." -ForegroundColor Cyan
#-----------------------------------------------------------------------------------------------------------------#
#-----------Function to add Session Mode---------------------------------------------------------------------------#
Function AddSessionMode {
    Write-Host "Enabling Sessions for SharePoint Web Application..." -foregroundcolor "Cyan"

    # Get the path to the config file from $WebApp
    # Prepare variables required to extract Web.Config from SPWebApplication   

    ##$WebAppConfigPath = "C:\inetpub\wwwroot\wss\VirtualDirectories\42275\Web.Config"
   
    Write-Host "Loading Web.Config as XML in " $wappconfigpath -ForegroundColor Cyan
    [xml]$xml = Get-Content $wappconfigpath
    Write-Host "Done" -ForegroundColor Green  
  
    # Check for system.web node
    $InProcNode = $xml.SelectSingleNode("//configuration/system.web")
    if ($InProcNode -ne $null)
    {
        Write-Host "InProc node exists in  section. Updating the node..." -ForegroundColor Cyan    

        # Check for
        $addSessionNode = $xml.SelectSingleNode("//configuration/system.web/sessionState[@mode='InProc']")
        if ($addSessionNode -ne $null)
        {
            Write-Host "'' entry found in Web.Config....So no updates made for this node." -ForegroundColor Cyan
        }
        else
        {
            # Recreate the  node
            $root = $xml.get_DocumentElement();        
            $addSessionNode = $xml.CreateNode('element',"sessionState","")   
            $addSessionNode.SetAttribute("mode", "InProc")
            $appSettingsNode =  $xml.SelectSingleNode("//configuration/system.web").AppendChild($addSessionNode)

            #Apply to Web.Config
            $xml.Save($wappconfigpath)

            Write-Host -NoNewline "'' entry created in Web.Config." -ForegroundColor Green
        }
    }

    Write-Host "Sessions enabled successfully." -foregroundcolor "Green"
} AddSessionMode
}
catch
{
                Write-Output $_
}
#-----------------------------------------------------------------------------------------------------------------#
$EndDate = Get-Date
Write-Host -ForegroundColor White "-----------------------------------"
Write-Host -ForegroundColor White "| Session State Enabled |"
Write-Host -ForegroundColor White "| Started on: $StartDate |"
Write-Host -ForegroundColor White "| Completed:  $EndDate |"
Write-Host -ForegroundColor White "-----------------------------------"
Stop-Transcript
Invoke-Item $LogFile     

Finally got the result as expected.

No comments:

Post a Comment