SharePoint Pals
 | Sign In
How to Backup and Deploy the Farm Solutions in SharePoint 2013 Using PowerShell
by Sathish Nadarajan 1 Dec 2015
Author
SharePoint MVP
Visits   
Today  :   2     Total  :    5464

In one of the Previous article, already we saw this snippet. But, I thought of refining it, much more a better version, so that it can be used on any project without any major modification. Conceptually, they are one and the same. The only thing, which I am adding here is,

1. Backup the WSPs before doing the deployment. If the WSP is going to be deployed for the first time, it will not stop our execution.

2. Write-the progress along with the seconds during the deployment and retraction.

3. Get the Environmental variables as an argument during the deployment.

4. Creating twoFolders WSPs and WSPBackups, so that more than one WSP can be deployed in a shot.

5. After deploying, clear the blob cache. That’s it.

The script looks like below.

 Add-PSSnapin "Microsoft.SharePoint.PowerShell"
 #Read arguement and store environment URL
 if($args[0] -eq 'DEV') {
 $WebApplicationUrl="https://DEVWebApplication/"
 }
 elseif ($args[0] -eq ‘UAT') {
 $WebApplicationUrl="https://UAT"
 }
 elseif ($args[0] -eq 'QA') {
 $WebApplicationUrl="https://QA/"
 }
  elseif ($args[0] -eq PROD) {
 $WebApplicationUrl="https://PROD/"
 }
 
 else {
 Write-Host -f Yellow "Environment not specified - please pass appropriate environment to deploy"
 exit
 }
 clear-host
  
 sleep 10
 
 $ErrorActionPreference = "Stop"
 $path = get-location
 $farm = Get-SPFarm
 
 #Define Path to New WSPs
 $wspfolderpath = "$path\WSPs"
 $WSPs = @()
 
 # Define Names of WSPs in Package
 foreach($filename in Get-ChildItem $wspFolderPath)
 {$script:WSPs += $filename}
 
 #Backup WSPs
 
 foreach ($WSPtoBackup in $WSPs) {
     try{
     $file = $farm.Solutions.Item("$WSPtoBackup").SolutionFile
     $file.SaveAs("$path\WSPBackups\$WSPtoBackup")
     write-host "$WSPtoBackup has been backed up."
     }
     catch{
     write-host -f Red "The solution:"
     write-host "$WSPtoBackup"
     write-host -f Red "Cannot not be backed up. It is not installed or found in the farm."
     }
 }
 function wait4timer($solutionName) 
 {    
     $solution = Get-SPSolution | where-object {$_.Name -eq $solutionName}    
     if ($solution -ne $null)     
     {        
         $solutionseconds = 0
         #Write-Host "Waiting to finish soultion timer job" -ForegroundColor Green      
         while ($solution.JobExists -eq $true )          
         {               
             write-progress -activity "Waiting to finish timer job" -status "$solutionseconds Seconds Elapsed"          
             sleep 1
             $solutionseconds++            
         }                
         Write-Host "Finished the timer job in $solutionseconds seconds" -ForegroundColor Green  
             }
 } 
 
 function DeployWSP 
 {      
     try
     {
         Write-Host "WebApplication  URL : $WebApplicationUrl" -ForegroundColor Green 
 
         # Get the Solution Node
         foreach($Solution in $WSPs)     
         {
             $wspName = $Solution.Name
             Write-Host "Solution Name : $wspName" -ForegroundColor Green 
 
             # Get the Path of the Solution
             $wspfullpath = "$wspFolderPath\$solution"
 
             Write-Host "Getting the Installed Solutions" -ForegroundColor Green 
             # Try to get the Installed Solutions on the Farm.
             $InstalledSolution = Get-SPSolution | Where-Object Name -eq $wspName
         
             # Verify whether the Solution is installed on the Target Web Application
             if($InstalledSolution -ne $null)
             {
                 if($InstalledSolution.Deployed)
                 {
                     Write-Host "Uninstall the Solution from All WebApplications" -ForegroundColor Green 
 
                     wait4timer($wspName)  
 
                     # Solution is installed in atleast one WebApplication
                     
                     
 
 
                     try{
                         Uninstall-SPSolution $wspName -AllWebApplications -confirm:$false
                     }
                     catch{
                         $ErrorMessage = $_.Exception.Message
                         if ($ErrorMessage.StartsWith("This solution contains no resources scoped for a Web application"))
                         {
                             Uninstall-SPSolution $wspName  -confirm:$false
                         }
                         else 
                         {
                             write-host "Failed to uninstall $wspname"
                             write-host $ErrorMessage
                         }
                     }
 
 
 
 
                     # Wait till the Timer jobs to Complete
                     wait4timer($wspName)   
 
                     Write-Host "Remove the Solution from the Farm" -ForegroundColor Green 
                     # Remove the Solution from the Farm
                    
                     Remove-SPSolution $wspName -Confirm:$false 
 
                     sleep 3
                 }
                 else
                 {
                     Write-Host "Remove the Solution from the Farm" -ForegroundColor Green 
 
                     wait4timer($wspName) 
 
                     # Solution not deployed on any of the Web Application.  Go ahead and Remove the Solution from the Farm
           
                     Remove-SPSolution $wspName -Confirm:$false 
 
                     sleep 3
                 }
             }
 
             wait4timer($wspName) 
 
             Write-Host "Add the Solution from the Farm" -ForegroundColor Green 
             # Add Solution to the Farm
          
             Add-SPSolution -LiteralPath "$wspFullPath"
             
             Write-Host "Deploy the Solution" -ForegroundColor Green 
             # Install Solution to the WebApplication
             try{
                 foreach($destwa in $WebApplicationUrl) 
                 {
                     install-spsolution -Identity $wspName -GACDeployment:$true -Force:$true -webapplication:$destwa
                     wait4timer($wspName)
                 }
             }
             catch{
                 $ErrorMessage = $_.Exception.Message
                 if ($ErrorMessage.StartsWith("This solution contains no resources scoped for a Web application"))
                 {
                   install-spsolution -Identity $wspName -GACDeployment:$true -Force:$true
                 }
                 else 
                 {
                   write-host "Failed to deploy $wspname"
                   write-host $ErrorMessage
                 }
             }
             
         
             # Let the Timer Jobs get finishes       
             wait4timer($wspName)    
 
             Write-Host "Successfully Deployed to the WebApplication" -ForegroundColor Green 
             #iisreset
         
         }
          
     }
     catch
     {
         Write-Host "Exception Occuerd on DeployWSP : " $Error[0].Exception.Message -ForegroundColor Red  
     }
 }
 
 
 try
 {
     DeployWSP
     iisreset
     foreach($WebApp in Get-spwebapplication)
     { 
     [Microsoft.SharePoint.Publishing.PublishingCache]::FlushBlobCache($webApp)
     Write-Host "Flushed the BLOB cache for:" $webApp
     }
     Write-Host "Script Execution Completed Successfully" -ForegroundColor Green 
 }
 catch
 {
     Write-Host "Custom Exception Happened on Main : " + $Error[0].Exception.Message -ForegroundColor Red  
 }
 

Happy Coding,

Sathish Nadarajan.

blog comments powered by Disqus

SharePoint Pals

Pals
SharePoint Pals, a community portal for SharePoint developers, Administrators and End Users. Let's join hands and share the point together.
Read this on mobile

Training

Angular Js Training In Chennai
Advanced Angular Js training with real world developer scenarios
Angular Js, Web Api and Ionic for .Net Developers
All in one client side application development for .Net developers
Angular Js For SharePoint Developers
Get ready for the future. Its no more just C#

Get Connected

SharePoint Resources

SharePoint 2013 and 2010 Web Parts
Free Web Parts with Source Code for SharePoint Community




SharePoint 2013 Books and Tutorials
Collection of free SharePoint 2013 books and tutorials (eBooks, pdfs)

Supported By

Contribute your article and be eligible for a one month Free Subscription for Plural Sight. The Author of the most popular New Article (published in the previous month) will be awarded with a Free One month Plural Sight Subscription. Article can be sent to articles@sharepointpals.com in a word document.

Related Resources

Recent Tweets

Twitter January 15, 00:25
How To Enable Target Value And Actual Value In #D3 Gauge Chart https://t.co/VxSi4QnNrC

Twitter January 15, 00:24
How To Open #SharePoint List Hyperlink Column In Modal #Popup Window https://t.co/EQ7HkoZDkX

Twitter January 15, 00:24
Quick Introduction To #Asp.NetCore And It’s Features https://t.co/zAXObHCFpH

Twitter January 15, 00:22
How To Configure #PerformancePoint Services To Use Secure Store In #SharePoint 2013 https://t.co/LEwnUoI7EY

Twitter January 15, 00:21
How To Block Or Disable #Office365 Services https://t.co/Yvp2VPFIRP

Follow us @SharePointPals
Note: For Customization and Configuration, CheckOutRecent Tweets Documentation