Nik Patel's SharePoint World

An adventure in SharePoint and Microsoft in general.

Archive for the ‘Admin PowerShell’ Category

Automated SharePoint 2010 Farm Level Solution Deployment and Retraction Process – Part IV – Using PowerShell Script

Posted by nikspatel on November 13, 2011

Article Series Content

This is fourth and final part of this article series and it provides step by step walk through on how to run deployment and retraction PowerShell script using batch files. Please note that even though this article walks through with batch files, you can still use PowerShell scripts directly to standardize the deployment process without batch files. Follow earliar articles in this series here at Part I, Part II, and Part III.

As I have described in earlier article, one of the assumptions in this script is all the batch files, log files, and WSPs exists in same directory during deployment process. If you are planning to have WSPs and log files in different directories other than batch files, you will have to update the script to make sure it’s not aware of current directory and manually pass in the full path for WSPs and Log files.

Let’s walk through final step by step walk through on how to create batch files and automate the custom SharePoint solution deployment and retraction process.

Step 1 – Prepare for Deployment and Retraction

  • Create Deployment Directory – (e.g. C:\CustomSolutions\Deployment\CustomHomePage)
  • Create Two Batch Files, Each for deployment and retraction (e.g. DeploySolution.bat and RetractSolution.bat)
  • Copy this PowerShell script from Part III to deployment directory (e.g. SPSolutionDeploymentScript.ps1).
  • Copy packaged SharePoint custom solution in same deployment directory (e.g. CustomHomePage.wsp)

Step 2 – Deployment Step

  • Copy following commands in the Deployment batch file (e.g.DeploySolution.bat). You may notice that first step in the batch file is to bypass the PowerShell execution policy. By default, PowerShell execution policy is retracted which would restrict loading PS1 files from the batch files and this step would bypass the PowerShell execution policy. Next step is to call the SPSolutionDeploymentScript.ps1 and passed in all the required parameters.

powershell -Command “& {Set-ExecutionPolicy bypass}” -NoExit
powershell -Command “& {.\SPSolutionDeploymentScript.ps1 -solutionName:CustomHomePage.wsp -webAppUrl:http://sp2010vm:1000 -siteUrl:http://sp2010vm:1000 -siteFeatureNames:@(‘CustomHomePage_CustomHomeWidgets’) -webFeatureNames:@(‘CustomHomePage_CustomHomePage’) -logFileName:DeploySolution.log -action:SD}” -NoExit

pause

 

  • To run the batch file, right click on the batch file and run as administrator.

  • This will run PowerShell script and deploy the solution and activate features on both site collection level and sub sites levels.

Step 3 – Retraction Step

  • Copy following commands for Retract batch file (e.g. RetractSolution.bat)

powershell -Command “& {Set-ExecutionPolicy bypass}” -NoExit
powershell -Command “& {.\SPSolutionDeploymentScript.ps1 -solutionName:CustomHomePage.wsp -webAppUrl:http://sp2010vm:1000 -siteUrl:http://sp2010vm:1000 -siteFeatureNames:@(‘CustomHomePage_CustomHomeWidgets’) -webFeatureNames:@(‘CustomHomePage_CustomHomePage’) -logFileName:RetractSolution.log -action:SR}” -NoExit

pause

  • To run the batch file, right click on the batch file and run as administrator. It will run PowerShell script and retract the solution and deactivate features from both site collection level and sub sites levels.

Transcript Logging
As you would see, both deployment and retraction process would create log files as transcripts. Having log files would be really helpful in the environment where administrators deploys the code in production environment and needed to communicate with developers if deployment or retraction process fails.

Posted in Admin PowerShell, Dev PowerShell | Leave a Comment »

Automated SharePoint 2010 Farm Level Solution Deployment and Retraction Process – Part III – Final Version of PowerShell Script

Posted by nikspatel on November 12, 2011

Article Series Content

This is third part of the article series and it provides the final/full version of PowerShell script built in earliar article to automate the SharePoint 2010 Farm Level Solution deployment/retraction process. If you haven’t read the first and Second parts of this series, I would recommend checking it out here at Part I and Part II.

Here is the final version of PowerShell script. Next article in this series will walk through step by step process of how to use this PowerShell script in real world using batch files to automate the process.

<# 
.DESCRIPTION 
    - Run this script to deploy/retract the farm level solution and activate/deactivate features

.GOAL
 - Build the most generic farm level soution deployment script
 
.ASSUMPTION
 - Batch files, log files, and WSPs exists in same directory during deployment process
 
.MAJOR FEATURES IMPLEMENTED
 - Parameters passed in from the batch file
 - Loading SharePoint PowerShell Plugin - Check if its already been loaded
 - Logging of Powershell script execution transcript, New file gets created for each run
 - Solution Deploy or Retract in single click
 - Waiting for  timer job execution while deploying and retracting solution
 - Nullable $siteFeatureNames and $webFeatureNames parameters to support deployment only option, no activation of features
 - Support Multiple Site and Web Level Features - Site feature and web features are passed in as array paramters
 - Support Activation of features at Multiple Webs - Activate/Deactivate Web Level features on all webs in site collection
 - Check for webapplication level resources to deploy or retract solutions at the web application level or all web application level
 - Prompt the script execution details with different color codes - green for major steps, yellow for detailed info, and red for errors

#>

param (
 [string]$solutionName = "$(Read-Host 'Enter the Solution WSP Name. [e.g. Sample.wsp]')",
 [string]$webAppUrl = "$(Read-Host 'Enter the Web Application URL. [e.g. <a href="http://sp2010vm]'/">http://sp2010vm]'</a>)",
    [string]$siteUrl = "$(Read-Host 'Enter the Site Collection URL. [e.g. <a href="http://sp2010vm/sites/site]'">http://sp2010vm/sites/site]'</a>)",
 [string[]]$siteFeatureNames = $null, #"$(Read-Host 'Enter the Site Level Features. [e.g. @('Feature1', 'Feature2')]')",
 [string[]]$webFeatureNames = $null, #"$(Read-Host 'Enter the Web Level Features. [e.g. @('Feature1', 'Feature2')]')",
    [string]$logFileName = "$(Read-Host 'Enter the Log File Name. [e.g. Sample.log]')",
    [string]$action = "$(Read-Host 'Enter [SD] to deploy solutions or [SR] to retract the solution')"
)

# Defination of main function
function main() {
 # find the current directory
 $currentDirectory = Get-Location
   
 # delete existing logfile
 $logFilePath = "$currentDirectory\$logFileName"
 if (Test-Path $logFilePath)
 {
  Remove-Item $logFilePath
 }
 
 # create new log file and start logging
 Start-Transcript $logFilePath

 # check to ensure Microsoft.SharePoint.PowerShell is loaded
 $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
 if ($snapin -eq $null)
 {
  Write-Host "Loading SharePoint Powershell Snapin"
  Add-PSSnapin "Microsoft.SharePoint.Powershell"
 }
 
 # deploy the solution
 if ($action -eq "SD")
 {
  Write-Host "Step 1 - Add Solution Package: " $solutionName -foregroundcolor Green
  AddSolution
  
  Write-Host "Step 2 - Deploy Solution Package: " $solutionName -foregroundcolor Green
  InstallSolution
  
  Write-Host "Step 3 - Timer Job to deploy the Solution Package" -foregroundcolor Green
  Wait4TimerJob

  Write-Host "Step 4 - Activate Site Collection Level Features" -foregroundcolor Green
  ActivateSiteFeatures
  
  Write-Host "Step 5 - Activate Web Level Features" -foregroundcolor Green
  ActivateWebFeatures
 } 
 
 # retract the solution
 if ($action -eq "SR")
 {
  Write-Host "Step 1 - Deactivate Web Level Features" -foregroundcolor Green
  DeactivateWebFeatures
  
  Write-Host "Step 2 - Deactivate Site Collection Level Features" -foregroundcolor Green
  DeactivateSiteFeatures
  
  Write-Host "Step 3 - Uninstall Solution Package: " $solutionName -foregroundcolor Green
  UnInstallSolution
  
  Write-Host "Step 4 - Timer Job to Retract the Solution Package" -foregroundcolor Green
  Wait4TimerJob
  
  Write-Host "Step 5 - Remove Solution Package: " $solutionName -foregroundcolor Green
  RemoveSolution
 }
 
 # stop the logging
 Stop-Transcript
}

# Add the solution package
# Adds a SharePoint solution package to the farm Solution gallery, It doesn't deploy the uploaded solution yet.
function AddSolution()
{
 $solution = Get-SPSolution | where-object {$_.Name -eq $solutionName}
 if ($solution -eq $null)
 {
  Write-Host "Adding solution package" -foregroundcolor Yellow
  $solutionPath = "$currentDirectory\$solutionName"
  Add-SPSolution -LiteralPath $solutionPath -Confirm:$false
 }
}

# Deploy the solution package 
# Deploys an installed SharePoint solution on all the WFE servers in the farm.
# Deploying solution in the farm installs the feature automatically. It installs all the features
# on each server at the farm, web, site collection, and site level but It doesn't activate them.
# Since it provisions the file on each WFE, it is a timer job.
function InstallSolution()
{
 $solution = Get-SPSolution | where-object {$_.Name -eq $solutionName}
 $solutionId = $solution.Id
 if ($solution -ne $null)
 {
  $solutionDeployed = Get-SPSolution -Identity $solutionId | where-object {$_.Deployed -eq "False"}
  if ($solutionDeployed -eq $null)
  {
   if ( $solution.ContainsWebApplicationResource )
   {
    Write-Host "Deploying solution package to web application: " $webAppUrl -foregroundcolor Yellow
    Install-SPSolution -Identity $solutionName -WebApplication $webAppUrl -GACDeployment -Confirm:$false
   }
   else
   {
    Write-Host "Deploying solution package to all web applications" -foregroundcolor Yellow
    Install-SPSolution -Identity $solutionName -GACDeployment -Confirm:$false
   }
  }
 }
}

# Activate the Site level features
function ActivateSiteFeatures()
{ 
 if ($siteFeatureNames -ne $null)
 {
  $spSite = Get-SPSite $siteUrl  
  foreach($siteFeatureName in $siteFeatureNames)
  {
   Write-Host "Trying to Activate Site Collection Level Feature: " $siteFeatureName -foregroundcolor Yellow
   $siteFeature = Get-SPFeature -site $spSite.url | where-object {$_.displayname -eq $siteFeatureName}
   if ($siteFeature -eq $null)
   {
    Write-Host "Activating Site Level Features at " $spSite.url -foregroundcolor Yellow
    Enable-SPFeature –identity $siteFeatureName -URL $spSite.url -Confirm:$false
   }
  }  
  $spSite.Dispose()
 }
}

# Activate the Web level features
function ActivateWebFeatures()
{
 if ($webFeatureNames -ne $null)
 {
  $spSite = Get-SPSite $siteUrl
 
  #Cycle through all webs in the collection and activate all the features
  foreach($spWeb in $spSite.AllWebs)
  { 
   foreach($webFeatureName in $webFeatureNames)
   {  
    Write-Host "Trying to Activate Web Level Features: " $webFeatureName -foregroundcolor Yellow
    $webFeature = Get-SPFeature -web $spWeb.url | where-object {$_.displayname -eq $webFeatureName} 
    if ($webFeature -eq $null)
    {
     Write-Host "Activating " $webFeatureName " at " $spWeb.url -foregroundcolor Yellow
     Enable-SPFeature –identity $webFeatureName -URL $spWeb.url -Confirm:$false
    }
   }
  }
  
  $spWeb.Dispose()
  $spSite.Dispose()
 }
}

# Deactivate the Web level features
function DeactivateWebFeatures()
{
 if ($webFeatureNames -ne $null)
 {
  $spSite = Get-SPSite $siteUrl
 
  #Cycle through all webs in the collection and deactivate all the features
  foreach($spWeb in $spSite.AllWebs)
  { 
   foreach($webFeatureName in $webFeatureNames)
   {  
    Write-Host "Trying to Deactivate Web Level Features: " $webFeatureName -foregroundcolor Yellow
    $webFeature = Get-SPFeature -web $spWeb.url | where-object {$_.displayname -eq $webFeatureName} 
    if ($webFeature -ne $null)
    {
     Write-Host "Deactivating " $webFeatureName " at " $spWeb.url -foregroundcolor Yellow
     Disable-SPFeature –identity $webFeatureName -URL $spWeb.url -Confirm:$false
    }
   }
  }
  
  $spWeb.Dispose()
  $spSite.Dispose()
 }
}

# Deactivate the Site level features
function DeactivateSiteFeatures()
{
 if ($siteFeatureNames -ne $null)
 {
  $spSite = Get-SPSite $siteUrl
  foreach($siteFeatureName in $siteFeatureNames)
  {
   Write-Host "Trying to Deactivate Site Collection Level Feature: " $siteFeatureName -foregroundcolor Yellow
   $siteFeature = Get-SPFeature -site $spSite.url | where-object {$_.displayname -eq $siteFeatureName}
   if ($siteFeature -ne $null)
   {
    Write-Host "Deactivating Site Level Features at " $spSite.url -foregroundcolor Yellow
    Disable-SPFeature –identity $siteFeatureName -URL $spSite.url -Confirm:$false
   }  
  } 
  $spSite.Dispose()
 }
}

# Retract the solution package
# Retracts a deployed SharePoint solution from the farm entirely for all web application or given web application.
# This step removes files from all the front-end Web server.
# Please note that retracting solution in the farm uninstalls the feature automatically, if it hasn't uninstalled using UnInstall-SPFeature.
# Since it removes the file on each WFE, it is a timer job.
function UnInstallSolution()
{
 $solution = Get-SPSolution | where-object {$_.Name -eq $solutionName}
 $solutionId = $solution.Id
 if ($solution -ne $null)
 {
  $solutionDeployed = Get-SPSolution -Identity $solutionId | where-object {$_.Deployed -eq "True"}
  if ($solutionDeployed -ne $null)   
  { 
   if ( $solution.ContainsWebApplicationResource )
   {
    Write-Host "Retracting solution package from web application: " $webAppUrl -foregroundcolor Yellow
    UnInstall-SPSolution -Identity $solutionName -WebApplication $webAppUrl -Confirm:$false
   }
   else
   {
    Write-Host "Retracting solution package from all web applications" -foregroundcolor Yellow
    UnInstall-SPSolution -Identity $solutionName -Confirm:$false
   }
  }
 }
}

# Remove the solution package
# Deletes a SharePoint solution from a farm solution gallery
function RemoveSolution()
{
 $solution = Get-SPSolution | where-object {$_.Name -eq $solutionName}
 if ($solution -ne $null)
 {
  Write-Host "Deleting the solution package" -foregroundcolor Yellow
  Remove-SPSolution $solutionName -Confirm:$false
 }
}

# Wait for timer job during deploy and retract
function Wait4TimerJob()
{
 $solution = Get-SPSolution | where-object {$_.Name -eq $solutionName}
 if ($solution -ne $null)
 {
  $counter = 1  
  $maximum = 50  
  $sleeptime = 2 
  
  Write-Host "Waiting to finish soultion timer job"
  while( ($solution.JobExists -eq $true ) -and ( $counter -lt $maximum ) )
  {  
   Write-Host "Please wait..."
   sleep $sleeptime 
   $counter++  
  }
  
  Write-Host "Finished the solution timer job"   
 }
}

#Run the Main Function
main


 

Posted in Admin PowerShell, Dev PowerShell | Leave a Comment »

Automated SharePoint 2010 Farm Level Solution Deployment and Retraction Process – Part II – Building PowerShell Script

Posted by nikspatel on November 12, 2011

Article Series Content

This is second part of the article series and it provides the step by step process of building PowerShell script to automate the SharePoint 2010 Farm Level Solution deployment/retraction process. If you haven’t read the first part of this series, I would recommend checking it out here.

Since PowerShell 2.0 is one of the pre-requisites, SharePoint Developer VM typically contains bits of PowerShell 2.0. Although Microsoft provides PowerShell 2.0 IDE for custom scripts, I like to use PowerGUI from Quest for PowerShell development - http://powergui.org/index.jspa.  Please check it out. It’s free download and provides nice debugging capabilities.

When I started creating PowerShell scripts to automate the SP2010 custom solution deployment/retraction process, one of my main goals was to build most generic farm level solution deployment script which would not only deploy/retract solutions and activate/deactivate features at the site collection level but also support activation/deactivation at all the sub sites level. If you are planning to deploy/retract solution at single site collection level, you can use this script right away without any changes. If you have more than one site collection, it would require slight modification.

Apart from most generic script, some of major features I wanted to support in this PowerShell script are as below.

  • It must support Parameters. Most of the environment specific information must be parameterized.
  • It should load SharePoint PowerShell Plugin automatically. If you have used SharePoint PowerShell Shell, it automatically loads this plugin but from custom windows PowerShell script, it must load manually and must check if it’s already loaded to avoid exceptions.
  • Since one of the goals of this script is to handover the deployment to SharePoint admins, Logging of PowerShell script execution transcript is key. It would create new file for each run. If Admins ever informs developers that your script has been failed, you can ask for this log file for troubleshoot
  • Major goal of this automated script to deploy or retract solutions in single click. Either you run PS manually or run using batch files; it should deploy/retract solutions and activate/deactivate features in single click.
  • As many of you know, during SharePoint Solution deployment and retraction process, SharePoint creates timer job to deploy and retract solutions from all the WFEs. We need to ask PowerShell to wait until these timer jobs complete their tasks. This PowerShell script should support waiting for timer job execution while deploying and retracting solution.
  • Support of Nullable $siteFeatureNames and $webFeatureNames parameters for deployment only option, no activation of features. Additionally you can pass one of these parameters, if Site or Web Level features are not applicable. Not all solutions would contain both web and site level features.
  • Support Multiple Site and Web Level Features – Site feature and web features are passed in as array parameters
  • Support Activation of features at Multiple Webs – Activate/Deactivate Web Level features on all webs in site collection
  • Check for web application level resources to deploy or retract solutions at the web application level or all web application level
  • Prompt the script execution details with different color codes – green for major steps, yellow for detailed info, and red for errors. If you are running these scripts manually on the server, you should be able to see the execution messages with different color codes.

To create the PowerShell script to automate Solution deployment/retraction process, please follow these steps. You can access final version of this script as 3rd part of this series here. Please note that I have posted this full working copy of this PowerShell script at TechNet Scripts library and you can find it here.

Step 1 – Define the Parameters to passed in PowerShell script

Define parameters to passed in web application URL, site collection URL, solution WSP Name, Site Level Features, Web Level Features, Log file name, and Action.  Last parameter would determine whether it’s deployment or retraction process. Ask calling application to enter SD for solution deployment and SR for solution retractions.

param (
 [string]$solutionName = "$(Read-Host 'Enter the Solution WSP Name. [e.g. Sample.wsp]')",
 [string]$webAppUrl = "$(Read-Host 'Enter the Web Application URL. [e.g. <a href="http://sp2010vm]'/">http://sp2010vm]'</a>)",
 [string]$siteUrl = "$(Read-Host 'Enter the Site Collection URL. [e.g. <a href="http://sp2010vm/sites/site]'">http://sp2010vm/sites/site]'</a>)",
 [string[]]$siteFeatureNames = $null, #"$(Read-Host 'Enter the Site Level Features. [e.g. @('Feature1', 'Feature2')]')",
 [string[]]$webFeatureNames = $null, #"$(Read-Host 'Enter the Web Level Features. [e.g. @('Feature1', 'Feature2')]')",
 [string]$logFileName = "$(Read-Host 'Enter the Log File Name. [e.g. Sample.log]')",
 [string]$action = "$(Read-Host 'Enter [SD] to deploy solutions or [SR] to retract the solution')"
)

Step 2 – Define the Main function.

As many of you know, PowerShell is all about defining functions and these functions can be called later to execute the PowerShell script logic. Main function is heard and sole of this script. Please note that since this PowerShell script would support only if Batch files, log files, and WSPs exists in same directory during deployment process, first step is to retrieve current location of the script. Next step is to create the log file to output the transcript. It would delete the log file, if it already exists.

One of the major tasks of the main function would be loading Microsoft.SharePoint.PowerShell snapin. This PS script will be using many of the SharePoint cmdlets available in Microsoft.SharePoint.PowerShell snapin and it is necessary to load before using the cmdlets. It is also necessary to check whether it’s been already loaded, otherwise this step would throw an error.

Depends on action switch, this function would run deployment or retraction process which will further call other secondary functions for deployment/retraction, activation/deactivation process.

# Defination of main function
function main() {
 # find the current directory
 $currentDirectory = Get-Location
   
 # delete existing logfile
 $logFilePath = "$currentDirectory\$logFileName"
 if (Test-Path $logFilePath)
 {
  Remove-Item $logFilePath
 }
 
 # create new log file and start logging
 Start-Transcript $logFilePath

 # check to ensure Microsoft.SharePoint.PowerShell is loaded
 $snapin = Get-PSSnapin | Where-Object {$_.Name -eq 'Microsoft.SharePoint.Powershell'}
 if ($snapin -eq $null)
 {
  Write-Host "Loading SharePoint Powershell Snapin"
  Add-PSSnapin "Microsoft.SharePoint.Powershell"
 }
 
 # deploy the solution
 if ($action -eq "SD")
 {
  Write-Host "Step 1 - Add Solution Package: " $solutionName -foregroundcolor Green
  AddSolution
  
  Write-Host "Step 2 - Deploy Solution Package: " $solutionName -foregroundcolor Green
  InstallSolution
  
  Write-Host "Step 3 - Timer Job to deploy the Solution Package" -foregroundcolor Green
  Wait4TimerJob

  Write-Host "Step 4 - Activate Site Collection Level Features" -foregroundcolor Green
  ActivateSiteFeatures
  
  Write-Host "Step 5 - Activate Web Level Features" -foregroundcolor Green
  ActivateWebFeatures
 } 
 
 # retract the solution
 if ($action -eq "SR")
 {
  Write-Host "Step 1 - Deactivate Web Level Features" -foregroundcolor Green
  DeactivateWebFeatures
  
  Write-Host "Step 2 - Deactivate Site Collection Level Features" -foregroundcolor Green
  DeactivateSiteFeatures
  
  Write-Host "Step 3 - Uninstall Solution Package: " $solutionName -foregroundcolor Green
  UnInstallSolution
  
  Write-Host "Step 4 - Timer Job to Retract the Solution Package" -foregroundcolor Green
  Wait4TimerJob
  
  Write-Host "Step 5 - Remove Solution Package: " $solutionName -foregroundcolor Green
  RemoveSolution
 }
 
 # stop the logging
 Stop-Transcript
}

Step 3 – Define all the Helper Functions

Define the AddSolution function which would use Add-SPSolution PowerShell command to add the solution to the configuration database. Please note that this step just adds the solution entry in the configuration database. It doesn’t deploy the solution or doesn’t deploy the custom files on the SharePoint Servers yet.

# Add the solution package
# Adds a SharePoint solution package to the farm Solution gallery, It doesn't deploy the uploaded solution yet.
function AddSolution()
{
 $solution = Get-SPSolution | where-object {$_.Name -eq $solutionName}
 if ($solution -eq $null)
 {
  Write-Host "Adding solution package" -foregroundcolor Yellow
  $solutionPath = "$currentDirectory\$solutionName"
  Add-SPSolution -LiteralPath $solutionPath -Confirm:$false
 }
}

Define the InstallSolution function which would use Install-SPSolution to deploy solution to specific web application or all web applications. If solution contains web part, module, event receiver, content type, or any other web application specific SharePoint project item, it would deploy solution to the specific web application otherwise, it would deploy to all the web applications. This step would call Install-SPFeature automatically and adds features entry in the configuration database.IT will also copy all the features and code files the SharePoint Root, copy DLLs into the GAC, and add necessary safe control entries to the Web.Config database.

# Deploy the solution package 
# Deploys an installed SharePoint solution on all the WFE servers in the farm.
# Deploying solution in the farm installs the feature automatically. It installs all the features
# on each server at the farm, web, site collection, and site level but It doesn't activate them.
# Since it provisions the file on each WFE, it is a timer job.
function InstallSolution()
{
 $solution = Get-SPSolution | where-object {$_.Name -eq $solutionName}
 $solutionId = $solution.Id
 if ($solution -ne $null)
 {
  $solutionDeployed = Get-SPSolution -Identity $solutionId | where-object {$_.Deployed -eq "False"}
  if ($solutionDeployed -eq $null)
  {
   if ( $solution.ContainsWebApplicationResource )
   {
    Write-Host "Deploying solution package to web application: " $webAppUrl -foregroundcolor Yellow
    Install-SPSolution -Identity $solutionName -WebApplication $webAppUrl -GACDeployment -Confirm:$false
   }
   else
   {
    Write-Host "Deploying solution package to all web applications" -foregroundcolor Yellow
    Install-SPSolution -Identity $solutionName -GACDeployment -Confirm:$false
   }
  }
 }
}

Define the ActivateSiteFeteatures function which would use Enable-SPFeature PowerShell command to activate all the site collection level features specified in $siteFeatureNames parameter. This would also add feature activation entry in the Content database features table.

# Activate the Site level features
function ActivateSiteFeatures()
{ 
 if ($siteFeatureNames -ne $null)
 {
  $spSite = Get-SPSite $siteUrl  
  foreach($siteFeatureName in $siteFeatureNames)
  {
   Write-Host "Trying to Activate Site Collection Level Feature: " $siteFeatureName -foregroundcolor Yellow
   $siteFeature = Get-SPFeature -site $spSite.url | where-object {$_.displayname -eq $siteFeatureName}
   if ($siteFeature -eq $null)
   {
    Write-Host "Activating Site Level Features at " $spSite.url -foregroundcolor Yellow
    Enable-SPFeature –identity $siteFeatureName -URL $spSite.url -Confirm:$false
   }
  }  
  $spSite.Dispose()
 }
}

Define the ActivateWebFeatures function which would use Enable-SPFeature PowerShell command to activate all the web level features specified in $webFeatureNames parameter in all the webs in specific site collection. This would also add feature activation entry in the Content database features table.

# Activate the Web level features
function ActivateWebFeatures()
{
 if ($webFeatureNames -ne $null)
 {
  $spSite = Get-SPSite $siteUrl
 
  #Cycle through all webs in the collection and activate all the features
  foreach($spWeb in $spSite.AllWebs)
  { 
   foreach($webFeatureName in $webFeatureNames)
   {  
    Write-Host "Trying to Activate Web Level Features: " $webFeatureName -foregroundcolor Yellow
    $webFeature = Get-SPFeature -web $spWeb.url | where-object {$_.displayname -eq $webFeatureName} 
    if ($webFeature -eq $null)
    {
     Write-Host "Activating " $webFeatureName " at " $spWeb.url -foregroundcolor Yellow
     Enable-SPFeature –identity $webFeatureName -URL $spWeb.url -Confirm:$false
    }
   }
  }
  
  $spWeb.Dispose()
  $spSite.Dispose()
 }
}

Define the DeactivateWebFeatures function which would use Disable-SPFeature PowerShell command to deactivate all the web level features specified in $webFeatureNames parameter in all the webs in specific site collection. This would also remove feature activation entry from the Content database features table.

# Deactivate the Web level features
function DeactivateWebFeatures()
{
 if ($webFeatureNames -ne $null)
 {
  $spSite = Get-SPSite $siteUrl
 
  #Cycle through all webs in the collection and deactivate all the features
  foreach($spWeb in $spSite.AllWebs)
  { 
   foreach($webFeatureName in $webFeatureNames)
   {  
    Write-Host "Trying to Deactivate Web Level Features: " $webFeatureName -foregroundcolor Yellow
    $webFeature = Get-SPFeature -web $spWeb.url | where-object {$_.displayname -eq $webFeatureName} 
    if ($webFeature -ne $null)
    {
     Write-Host "Deactivating " $webFeatureName " at " $spWeb.url -foregroundcolor Yellow
     Disable-SPFeature –identity $webFeatureName -URL $spWeb.url -Confirm:$false
    }
   }
  }
  
  $spWeb.Dispose()
  $spSite.Dispose()
 }
}

Define the DeactivateSiteFeatures function which would use Disable-SPFeature PowerShell command to deactivate all the site collection level features specified in $siteFeatureNames parameter. This would also remove feature activation entry from the Content database features table.

# Deactivate the Site level features
function DeactivateSiteFeatures()
{
 if ($siteFeatureNames -ne $null)
 {
  $spSite = Get-SPSite $siteUrl
  foreach($siteFeatureName in $siteFeatureNames)
  {
   Write-Host "Trying to Deactivate Site Collection Level Feature: " $siteFeatureName -foregroundcolor Yellow
   $siteFeature = Get-SPFeature -site $spSite.url | where-object {$_.displayname -eq $siteFeatureName}
   if ($siteFeature -ne $null)
   {
    Write-Host "Deactivating Site Level Features at " $spSite.url -foregroundcolor Yellow
    Disable-SPFeature –identity $siteFeatureName -URL $spSite.url -Confirm:$false
   }  
  } 
  $spSite.Dispose()
 }
}

Define the UnInstallSolution function which would use UnInstall-SPSolution to retract solution from specific web application or all web applications. If solution contains web part, module, event receiver, content type, or any other web application specific SharePoint project item, it would retract solution from the specific web application otherwise, it would retract from all the web applications. This step would call UnInstall-SPFeature automatically and removes features entry from the configuration database. IT will also delete all the features and code files from the SharePoint Root, remove DLLs from the GAC, and remove necessary safe control entries from the Web.Config database.


# Retract the solution package
# Retracts a deployed SharePoint solution from the farm entirely for all web application or given web application.
# This step removes files from all the front-end Web server.
# Please note that retracting solution in the farm uninstalls the feature automatically, if it hasn't uninstalled using UnInstall-SPFeature.
# Since it removes the file on each WFE, it is a timer job.
function UnInstallSolution()
{
 $solution = Get-SPSolution | where-object {$_.Name -eq $solutionName}
 $solutionId = $solution.Id
 if ($solution -ne $null)
 {
  $solutionDeployed = Get-SPSolution -Identity $solutionId | where-object {$_.Deployed -eq "True"}
  if ($solutionDeployed -ne $null)   
  { 
   if ( $solution.ContainsWebApplicationResource )
   {
    Write-Host "Retracting solution package from web application: " $webAppUrl -foregroundcolor Yellow
    UnInstall-SPSolution -Identity $solutionName -WebApplication $webAppUrl -Confirm:$false
   }
   else
   {
    Write-Host "Retracting solution package from all web applications" -foregroundcolor Yellow
    UnInstall-SPSolution -Identity $solutionName -Confirm:$false
   }
  }
 }
}

Define the RemoveSolution function which would use Remove-SPSolution PowerShell command to remove the solution from the configuration database. Please note that this step removes the solution entry from the configuration database and completely cleans up the custom solution deployed on the SharePoint environment. 

# Remove the solution package
# Deletes a SharePoint solution from a farm solution gallery
function RemoveSolution()
{
 $solution = Get-SPSolution | where-object {$_.Name -eq $solutionName}
 if ($solution -ne $null)
 {
  Write-Host "Deleting the solution package" -foregroundcolor Yellow
  Remove-SPSolution $solutionName -Confirm:$false
 }
}

Implement the Wait4TimerJob which will be helper function used after InstallSolution and UnInstallSolution process to ask PowerShell script to wait until solution properly deployed or retracted from all the servers in the farm. It checks timer job status to check whether it’s been completed or not.

# Wait for timer job during deploy and retract
function Wait4TimerJob()
{
 $solution = Get-SPSolution | where-object {$_.Name -eq $solutionName}
 if ($solution -ne $null)
 {
  $counter = 1  
  $maximum = 50  
  $sleeptime = 2 
  
  Write-Host "Waiting to finish soultion timer job"
  while( ($solution.JobExists -eq $true ) -and ( $counter -lt $maximum ) )
  {  
   Write-Host "Please wait..."
   sleep $sleeptime 
   $counter++  
  }
  
  Write-Host "Finished the solution timer job"   
 }
}

Step 4 – Call the Main Function to Execute PowerShell Script Logic

Last step of the PowerShell script is to call the “Main” function defined earlier. This will ask PowerShell engine to run deployment and retraction logic.

#Run the Main Function
main

This concludes the step by step PowerShell script creation process for automated SharePoint solution deployment and retraction process. Next article in this series will provide full version of this PowerShell script and walk through step by step process of how to use this PowerShell script in real world using batch files to automate the process.

Posted in Admin PowerShell, Dev PowerShell | Leave a Comment »

Automated SharePoint 2010 Farm Level Solution Deployment and Retraction Process – Part I – Basics

Posted by nikspatel on November 12, 2011

Article Series Content

If you have been developing custom solutions on SharePoint 2010 platform, having knowledge of how to move your code from developer’s machine to server environment using scripts is mandatory. It’s been best practice for a while to script deployment process while moving code to server environment. It always surprises me seeing developers manually logging on the servers and run PowerShell commands to deploy/retract custom solutions and activate/deactivate features. If you are SharePoint administrators, it is most important that you would ask your development team to standardize the deployment process using scripts.

During SharePoint 2007, STSADM was available to script the custom solutions deployment/retraction process. In SharePoint 2010, Microsoft has introduced PowerShell as preferred technology to script custom solutions deployment/retraction process. This blog series will outline what are the major steps required for farm level custom solution deployment and retraction process for SharePoint 2010, how you can automate the process using PowerShell, and how you can automate the deployment execution using windows batch files.

This is first part of this article series and it provides the overview of the SharePoint 2010 Farm Level Solution deployment/retraction process.

In SharePoint 2010, both Solutions and features can be managed by Browser Interface, PowerShell, or STSADM. You must be farm administrators to manage farm level features, Manage Web permission at the root level site (site collection administrator) to manage site collection features, and Manage Web permission (site owners) to manage site level features.

Following two tables outlines what is supported and commands available at the browser, STSADM, and PowerShell.

Solutions Actions Central Admin (System Settings-> Farm Management -> Manage Farm Solutions)          PowerShell                      STSADM                       
View Solutions Yes Get-SPSolution -o enumsolutions
Add Solution – Add Solutions to Farm Solutions Gallery Not Supported Add-SPSolution -o addsolution
Deploy Solution – Deploys Solutions to the web applications Yes Install-SPSolution -o deploysolution
Update Solution – Update the deployed solution Not Supported Update-SPSolution -o upgradesolution
Retract Solution – retract solutions from the web applications Yes Uninstall-SPSolution -o retractsolution
Remove Solution – Remove the solution from the farm solutions gallery Yes Remove-SPSolution -o deletesolution
 
Feature Actions   Farm, Application, Site, and Web Level Features Page      PowerShell                        STSADM                     
View Features – View features at the farm, web application, site collection, or site scope Yes Get-SPFeature Not Supported
Install Feature – Install feature at the farm, web application, site collection, or site scope No Install-SPFeature -o installfeature
Activate Feature  – Activate feature at the farm, web application, site collection, or site scope Yes Enable-SPFeature -o activatefeature
Deactivate Feature – Deactivate feature at the farm, web application, site collection, or site scope Yes Disable-SPFeature -o deactivatefeature
Uninstall Feature – Uninstall feature at the farm, web application, site collection, or site scope No Uninstall-SPFeature -o uninstallfeature
 
Typical Order of the Farm Solutions Deployment using the Power Shell Commands
If you haven’t been familiar with the SharePoint Deployment and Retraction cycle, here is the high level diagram depicting the process. Although upgrading solutions and features is not included in visual digaram, Please note that typical steps would be  => Add Solution -> Deploy Solution -> Install Feature -> Activate Feature -> Update Solution -> Upgrade Feature -> Deactivate Feature -> Uninstall Feature -> Retract Solution -> Delete Solution
 
 
Since STSADM has been deprecated (still supported) in favor of PowerShell, this article series will use PowerShell from here on. Here is the high level overview of all the PowerShell commands to deploy/retract solutions, activate/deactivate features, and upgrading solutions and features.
  • Add Solution – Add-SPSolution
    • Adds a SharePoint solution package to the farm Solution gallery, It doesn’t deploy the uploaded solution yet.
    • Add-SPSolution -LiteralPath “c:\Project Initiation Web Parts.wsp”
  • Deploy Solution – Install-SPSolution
    • Deploys an installed SharePoint solution on all the WFE servers in the farm. This command also installs all the features on each server at the farm, web, site collection, and site level but It doesn’t activate them.
    • Since it provisions the file on each WFE, it is a timer job. It may take while to provision the files.
    • Install-SPSolution –Identity “Project Initiation Web Parts.wsp” –WebApplication http://sp2010vm -GACDeployment
    • Major Parameters
      • Identity – Name of the fully trusted solution
      • AllWebApplications or Web Application with URL – URL of the web application where solution will be deployed. For Global deployment for all web applications, specify AllWebApplications
      • Local – Solution will be deployed on only server where this command is being run
      • GACDeployment – To deploy artifacts into GAC
      • Time – Schedule the solution deployment at specified time. If this parameter is not specified, solution deployment process would run immediately during next timer job process
    • Major File System changes
      • Global Assembly Cache – C:\Windows\assembly (e.g. Deploys the DLL into GAC)
      • Web Application Directories – C:\inetpub\wwwroot\wss\VirtualDirectories (e.g. Updates the web.config and adds web part safe control entries – C:\inetpub\wwwroot\wss\VirtualDirectories\80)
      • SharePoint Root Folder – C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14
        • Adds new feature directory and provision the web part files – C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES\
        • Adds new user controls  – C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\CONTROLTEMPLATES\
  •  Install Feature – Install-SPFeature (Optional Step – included in Install-SPSolution)
    • Deploying solution in the farm installs the feature automatically. This is preferred method. No need to manually run this command.
    • Install-SPFeature <FeatureFolderName>
  • Activate Feature – Enable-SPFeature
    • Enables installed SharePoint Feature at the given scope. If the feature is a farm feature, no URL is needed. Otherwise, provide the URL where the feature is to be activated (explicit scope is not needed).
    • Enable-SPFeature –identity “MyCustomFeatureNameorGUID” -URL http://sp2010vm
    • Identity parameter is feature folder name or feature GUID
  • Update Solution – Update-SPSolution
    • Upgrades a deployed SharePoint solution in the farm. Use this cmdlet only if a new solution contains the same name, same set of files, and features as the deployed solution.
    • If files and features are different and feature version is not upgraded, the solution must be retracted and redeployed by using the Uninstall-SPSolution and Install-SPSolution cmdlets, respectively.
    • Update-SPSolution -Identity contoso_solution.wsp -LiteralPath c:\contoso_solution_v2.wsp -GACDeployment
  • Deactivate Feature – Disable-SPFeature
    • Disables installed SharePoint Feature at a given scope. If the scope of the Feature is the farm, the URL is not needed. Otherwise, provide the URL at which this Feature is to be deactivated (explicit scope is not needed).
    • Disable-SPFeature –identity “MyCustomFeatureNameorGUID” -URL http://sp2010vm
    • Identity parameter is feature folder name or feature GUID
  • Uninstall Feature  - UnInstall-SPFeature (Optional Step – included in UnInstall-SPSolution)
    • Retracting solution in the farm uninstalls the feature automatically. This is preferred method. No need to manually run this command unless solution retraction process couldn’t uninstall features for some reasons.
    • UnInstall-SPFeature <FeatureFolderName>
  • Retract Solution – Uninstall-SPSolution
    • Retracts a deployed SharePoint solution from the farm entirely for all web application or given web application.  If web application is not specified,  this cmdlet removes files from all the front-end Web server.
    • Since it removes the file on each WFE, it is a timer job. It may take while to delete the files.
    • Uninstall-SPSolution –Identity “Project Initiation Web Parts.wsp” –WebApplication http://sp2010vm
    • Most items that go in the content database are not overwritten or deleted for you when the feature reinstalls or solutions are retracted. Most items that go on the file system are overwritten or deleted during the retraction process. There is exception to this rule – redeploying web parts deletes the web part from the web part gallery and imports the new updated version, if web part deployment conflict resolution property is set to the Automatic. Other options are None to ignore over write and prompt.
    • Removes deployed components from the file system
      • Deletes the DLL from the GAC – C:\Windows\assembly
      • Updates the web.config and removes web part safe control entries – C:\inetpub\wwwroot\wss\VirtualDirectories\80
      • Deletes the feature directory – C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\TEMPLATE\FEATURES\ProjectInitiationToolWebParts_ProjectInit
  • Delete Solution – Remove-SPSolution
    • Deletes a SharePoint solution from a farm solution gallery
    • Don’t deploy the solution when its being removed by this command. It may put the solution in the inconsistent state. Always verify that solution is removed from the farm solution gallery before kicking off the deploy process of same solution.
    • Remove-SPSolution -Identity “Project Initiation Web Parts.wsp”

That concludes this overview article. Hopefully you have gained enough knowledge of SharePoint 2010 custom deployment and retraction process. Next article in this series will discuss steps required to build PowerShell script to automate the deployment/retraction solutions process.

Posted in Admin PowerShell, Dev PowerShell | Leave a Comment »

Create New Site Collection in the New Content Database in SharePoint 2010

Posted by nikspatel on November 10, 2010

If you want to create a new site collection in the specific database, there are several different options available in the SharePoint 2010.

From the central administration site, you can create the site collection in the specific database with the following workaround. The downside of this approach is you have to temporarily take down the all the content databases in the given web application except the database where you want to create the new site collection.

  • Create a new content database for the given web application (Central Administration -> Manage Content Databases)
  • Detach/remove the content databases except the new one (Central Administration -> Manage Content Databases)
  • Create the new site collection from the central admin (Central Administration -> Create Site Collection)
  • Attach/Add the offline content databases (Central Administration -> Manage Content Databases)

Better way to approach creating the new site collection in the specific content database is to use New-SPContentDatabase and New-SPSite PowerShell commands.

  • Step 1- Add New Content DB to the Web Application

New-SPContentDatabase -Name WSS_Content_Accounts -WebApplication http://sp2010vmStep

  • Step 2- Create New Site Collection with Top Level Site Based on Team Site Template in the New Content DB

New-SPSite http://sp2010vm/sites/accounts -OwnerAlias “Niks\Administrator” -ContentDatabase WSS_Content_Accounts -Name “Account Sites” -Description “Account Sites Container” -Template “STS#0″

Hope this will be helpful.

Posted in Admin PowerShell | Leave a Comment »

 
Follow

Get every new post delivered to your Inbox.