Tuesday, May 11, 2010

SharePoint 2010 Deployment: Powershell Script

Pre-SharePoint 2010 developers are familiar with Stsadm command. The general scenario of SharePoint 2007 deployment is to develop a batch file with stsamd commands. A generic deployment includes the following steps:
  • Deactivate Features
  • Uninstall Features
  • Retract Solution
  • Delete Solution
  • Add Solution
  • Deploy Solution
  • Install Features
  • Activate Features

SharePoint 2007 Deployment Script:

I’ll first describe how stsadm command file looks like implementing the above steps. You can put the following script in a batch file and then clicking on the batch file in SharePoint server, will deploy the solution. The solution and the batch file need  to be in the same folder. The first line of the script (cd /d %~dp0) will change the current directory to the script directory.
--Change script directory to current directory 
cd /d %~dp0 
@SET STSADM="c:\program files\common files\microsoft shared\web server extensions\12\bin\stsadm" 
@SET SITEURL="http://localhost" 

echo Deativating 'MyFeature' feature. 
%stsadm% -o deactivatefeature -name MyFeature -url %SITEURL% -force  
echo Uninstalling 'MyFeature' feature. 
%stsadm% -o uninstallfeature -name MyFeature -force  

echo Retracting solution 'MySolution.wsp' 
%stsadm% -o retractsolution -name MySolution.wsp -immediate -allcontenturls %stsadm% -o execadmsvcjobs  
echo deleting solution 'MySolution.wsp' 
%stsadm% -o deletesolution -name MySolution.wsp -override  

echo adding solution 'MySolution.wsp'
%stsadm% -o addsolution -filename MySolution.wsp  
echo deploying solution 'MySolution.wsp' 
%stsadm% -o deploysolution -name MySolution.wsp -url %SITEURL% -immediate -allowGacDeployment -force 
%stsadm% -o execadmsvcjobs 
echo Installing 'MyFeature' feature. 
%stsadm% -o installfeature -name MyFeature -force  
echo activating 'MyFeature' feature. 
%stsadm% -o activatefeature -name MyFeature -url %SITEURL% -force  
iisreset /restart /noforce /timeout:60 
File: SharePoint 2007 Script for Deployment

PowerShell Scripting Basic, every SharePoint Developer Should Know

In SharePoint 2010 stsadm is supported but powershell commands are recommended to use. To know how to run SharePoint powershell script, let’s get an overview of PowerShell. I’ll try to provide a gist on Powershell so that you can write your own Script for SharePoint. As as SharePoint developer we don’t need to be expert in PowerShell script but we need to know the basic syntax.
 PowerShell command format: Powershell command has two parts: verb and noun. For example, to get current date, you need to execute command get-date. Here get is verb then a hyphen(-) and finally date which is noun. Powershell is not case sensitive. But its good practice to use Caml case in command. The following command uses verb-noun format to get current date.
Get Help on PowerShell Command: To get help for a command you can use Get-Help command. The following command is used to get help on Get-Date:
Get-Help Get-Date
You can even type the verb part including hyphen and then press tab. You’ll then get the all commands starting with the verb.
PowerShell command execution Permission: Before you execute any command, you need to enable PowerShell to execute command. You can get the current execution policy by running the following command:
The result of the command might be one of the followings:
  • Restricted
  • AllSigned
  • RemoteSigned
  • Unrestricted
  • Bypass
  • Undefined
To execute command or run scripts, you can set execution policy to ReomteSigned but based on your security consideration, you can use different options. To set execution policy, you can run the following command:
Set-ExecutionPolicy RemoteSigned
Run a PowerShell Script: To run a PowerShell script, you need put the file name in the PowerShell command prompt. But there are few conventions/restrictions that you need to follow.
  • To run a script file you need to type complete path of the script file. The complete path may be in the form ‘.\folder\subfolder\script.ps1’ or a full path like ‘c:\folder\subfolder\script.ps1’
  • To execute a script you need to use the format of & ScriptPath format. If the file path has space then use double quotation to enclose the path. So to execute a file you can use the command like below:
& “C:\My Scripts\Script.ps1”
  • If you want to run PowerShell script from Run window then you can do so by putting the following command in Run window:
Powershell –NoExit & ‘C:\My Scripts\Scripts.ps1’
One thing to remember in the above script is that single quote is used instead of double quote when you will run the above command from Run window. Single quote must be used for file path if the file path has space. Double quote will not work in this case.
  • Variables in PowerShell are identified by putting a  $ prefix. You’ll find how the variable is used in the section “A Sample PowerShell Script”
  • PowerShell script file is saved with extension .ps1
A Sample PowerShell Script:
Let’s say you have a PowerShell script (as shown below) in a file named script.ps1. Now You want to run the following powershell script (in a file Script.ps1) from Run window. The script will add two numbers and print the output.
echo 'setting a value for a'
echo 'setting a value for a'
echo 'adding a and b'
echo "reslut is $c"

The variables in the above script are prefixed by $. Take a close look at the last echo. The echo has a $c in the double quotation. Remember, you can refer a variable name in double quotation string (as in the last echo in the above script). But the same is not true for single quote. If you would use the $c inside single quote then it would print back the $c. Single quote is considered as literal string in PowerShell.

SharePoint 2010 Deployment

In SharePoint 2010, you can use PowerShell script for deploying SharePoint solution/features. Let’s first take a look at how the deployment script will look like
PowerShell Deployment Script: Deployment in SharePoint 2010 still has the same eight steps (Deactivate Features, Uninstall Features…..) as described at the beginning of this post. The following script deploy a solution:
function WaitForJobToFinish([string]$SolutionFileName)
    $JobName = "*solution-deployment*$SolutionFileName*"
    $job = Get-SPTimerJob | ?{ $_.Name -like $JobName }
    if ($job -eq $null) 
        Write-Host 'Timer job not found'
        $JobFullName = $job.Name
        Write-Host -NoNewLine "Waiting to finish job $JobFullName"
        while ((Get-SPTimerJob $JobFullName) -ne $null) 
            Write-Host -NoNewLine .
            Start-Sleep -Seconds 2
        Write-Host  "Finished waiting for job.."

Add-PsSnapin Microsoft.SharePoint.PowerShell
$SolutionPath=$CurrentDir + "\"+$solutionName 
Write-Host 'Going to disable feature'
disable-spfeature -identity Limeco.UI.WebParts_LimecoWebPartFeature -confirm:$false -url http://localhost
Write-Host 'Going to uninstall feature'
uninstall-spfeature -identity Limeco.UI.WebParts_LimecoWebPartFeature -confirm:$false -force
Write-Host 'Going to uninstall solution'
Uninstall-SPSolution -identity $solutionName  -allwebapplications -confirm:$false

Write-Host 'Waiting for job to finish'

Write-Host 'Going to remove solution'
Remove-SPSolution –identity $solutionName -confirm:$false
Write-Host 'Going to add solution'
Add-SPSolution $SolutionPath
Write-Host 'Going to install solution to all web applications'
Install-SPSolution –identity $solutionName –Allwebapplications –GACDeployment

Write-Host 'Waiting for job to finish' 

Write-Host 'Going to enable Feature' 
Enable-spfeature -identity Limeco.UI.WebParts_LimecoWebPartFeature -confirm:$false -url http://localhost 

Remove-PsSnapin Microsoft.SharePoint.PowerShell
File: Myscript.ps1

The first thing in the above script is a function WaitForJobToFinish which is used to make sure jobs are finished executing before moving on. This method is similar like the command ‘stsadm –o execadmsvcjobs’ in SharePoint 2007. In the above script, the line ‘Add-PSSnapin’load the SharePoint PowerShell script. If you already using SharePoint 2010 Management Shell (Which is a PowerShell extension already) then this line should be removed. In the above script Write-Host is just like print function that print a string in the console. FYI, when you pass arguments to an PowerShell script, the arguments are kept in a PowerShell variable $Args. You can access any arguments by assessing it $Args[index]. I think the command in the above script is self-explanatory. The –confirm:$false is for not to prompt user for confirmation. In the above script you need to pass the solution directory.
Automate the Deployment Script: To automate the powershell Script you need to put the above script in a PowerShell scipt file(having ps1 extension). Let’s say you have you script in a file named as myscript.ps1. Now you need to run the script you need a batch file which will execute the script file. The script file may be like one shown below:
cd /d %~dp0
powershell -noexit -file    ".\MyScript.ps1" "%CD%"

 File: MyCommand.bat
In the above command, the first line change the current directory to the location from where the batch file is run. Then I have run the PowerShell with the MyScript.ps1 file and passed the current directory as argument (%CD%)


I think stsadm command was simple and easy to use. PowerShell is too much powerful and extensible. You can do almost all kinds of SharePoint programming with PowerShell script. My personal view is that we, SharePoint developers, don’t need to be expert in PowerShell but we need to have basic knowledge of “How to use PowerShell Script for SharePoint Deployment/Maintenance?”. There are already much activities on web around PowerShell and SharePoint. Few useful links related to PowerShell and SharePoint are given below:
Some Useful CodePlex links:
Here is a Visual Studio 2010 extension for SharePoint PowerShell Scripting:
Here is a tool called PowerGui that is handy for editing PowerShell script:

The concept for waiting for job to finish, I have taken from the following link:


  1. We have host header site collection in a web app in sharepoint 2010 and when we do redeployment of wsp, nothing gets updated but suprising thing is root site collection which is not host header site collection inside same web app gets updated master page/ page layouts. I tried to activate/deactivate feature but nothing getting updated and I can not delete existing page layouts/ master page as they are being used by number of pages and that is not the solution I am looking for.

    Can anybody guide on how to deploy wsp in host header site collection in sharepoint 2010/

  2. Had u tried to restore on url that is defined in alternate access mapping for default zone?

  3. There is an app to remember sharepoint powershell commands http://sppower.codeplex.com/

  4. Hi,

    If I want Deactivate, Retract, Remove, Add, Deploy & Activate multiple wsp files by one script...

    Currently We are using the following script for single wsp...

    Write-Host 'Powershell Script will initialize parameters'
    $SolutionPath=$CurrentDir + "\"+$solutionName
    $logfile=$CurrentDir + "\log.log"
    $SiteUrl = "server.com"
    Start-Transcript $logfile

    $errorActionPreference = 'Inquire'

    Write-Host 'Powershell Script will now disable feature:' $featureName
    Disable-SPFeature -Identity $featureName -url $SiteUrl -Confirm:$false -force

    Write-Host 'Powershell Script will now retract solution:' $solutionName
    Uninstall-SPSolution -Identity $solutionName -WebApplication $SiteUrl -Confirm:$false
    Start-Sleep -s 15

    Write-Host 'Powershell Script will now remove solution:' $solutionName
    Remove-SPSolution -Identity $solutionName -Confirm:$false

    Write-Host 'Powershell Script will now add solution:' $solutionName
    Add-SPSolution $SolutionPath

    Write-Host 'Powershell Script will now deploy solution:' $solutionName
    Install-SPSolution -Identity $solutionName -WebApplication $SiteUrl -GACDeployment
    Start-Sleep -s 15

    Write-Host 'Powershell Script will now enable feature:' $featureName
    Enable-SPFeature -Identity $featureName -url $SiteUrl -Confirm:$false


  5. Awesome article. Thank you very much.
    I knew other deployment steps but wanted Timer job wait script.
    Your function did great job.

    Thanks a lot...

  6. Hi Sohel,
    Thanks,Your script really did well, but from the below line, it deploy all web.
    Install-SPSolution –entity $solutionName –allwebapplications –ACDeployment

    To deploy a particular Web, it should like:

    Install-SPSolution –Identity SharePointProject.wsp –WebApplication http://paulsp.com -GACDeployment

    Please guide if there is any other way where .wsp can be deployed to one single web.

    Thanks again for the helpful post.