Thursday, March 7, 2013

Automating SharePoint site backup using Power Shell and windows Task Scheduler

SharePoint administrators need to run regular backups using PowerShell, the STSADM tool or in Central Administration. But taking these backups on a daily basis can be a tedious process, hence either we can sit back and take backup, waiting for it to get over or we can go home and sleep on the couch, while the PowerShell and Task Scheduler take cares of the rest.

Creating PowerShell script to take Backup 

I have included the whole script first which i have then explained below in phases


PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
try
{
$today = (Get-Date -Format dd-MM-yyyy)
$backupDirectory = "D:\Backup\DailySiteCollectionBackUp\$today"
# Backup file Location
$backupFile = "D:\Backup\DailySiteCollectionBackUp\$today\Backup.dat"
# Log file location
$logFile = "$backupDirectory\BackupLog.log"
# Address of the Site Collection to backup
# Location of the Backup Folder
if (-not (Test-Path $backupDirectory))
{
[IO.Directory]::CreateDirectory($backupDirectory)
#New-Item $logPath -type $backupDirectory
}
# Get backup start date and time
$backupStart = Get-Date -format "MM-dd-yyyy HH.mm.ss"
# creates a log file Start-Transcript -Path
Start-Transcript -Path $logFile
# This will actually initiate the backup process.
Write-Host
Write-Host
Write-Host "Backup starting at $backupStart for $Site "
Write-Host "******************************************"
Backup-SPSite -Identity $Site -Path $backupFile -Force
$backupComplete = Get-Date -format "MM-dd-yyyy HH.mm.ss"
Write-Host
Write-Host
Write-Host "Backup Completed at $backupComplete for $Site "
Write-Host "******************************************"
Stop-Transcript
}
Catch
{
$ErrorMessage = $_.Exception.Message
write "$today BackUp Failed $ErrorMessage ">>$logFile
}


a) It will load the SharePoint snap IN
Including Powershell SnapIn
Including PowerShell SnapIN
b) It will create a folder with the current Date if not present.

Creating BackUp Folder
Note: Do change the path according to the place where you want to store the backup.

c) Then we will run the “Start Transcript/Stop-Transcript” block command. This will log all command that the user types and all output that appears on the console. Here we will require to pass the log file name. Between the “Start Transcript/Stop-Transcript” we will take the backup with the Backup-SPSite which will take the backup of the specified site

Create Backup Folder

Note: Start Transcript/Stop-Transcript command does not runs on the PowerShell ISE, this will run only on the console, which is the way we are going to do while running it from windows task scheduler.

d) Now after the whole script is created save it with a .ps1 extension.
In the above we created the script which will take the backup of a site collection and will store it in new folder based on the current date. This script has been saved as .ps1 (PowerShell script) file. Now we want this script to run every day at 10:00 PM when I am taking rest at home. This automation can be achieved easily by windows task scheduler.

How to use windows scheduler to automate the Backup on a daily basis

a) First load the Task Scheduler from Start >> All Programs >> Accessories >> System Tool>> Task Scheduler. I am using the version which ships with windows server 2008 R2 edition, but the concept should be same for other release.

b) To create a new Task, click Create Task from the right hand side “Actions Panel”.

c) This will open a Create Task window which will have first tab as General; here we need to provide the following basic information.

General Tab

  1. Name of the Task like “SharePoint Backup”. A Description which is not mandatory
  2. Select the User Account under which the following task will run. Ensure that the user account has the necessary permissions to use the PowerShell on the SharePoint farm, permission to perform script action on the SharePoint.
  3. Select Run whether the user is logged in or not and tick the Do not store password checkbox. This is necessary because at the time of backup being taken you may not be logged in.
  4. Also enable the Run with highest privileges option. I would recommend testing the script from Task Scheduler with the option disabled and only enable if the script does not work without it.

d) In the “Triggers Tab
  1. Click New and in the “New Trigger”
  2. In “Begin the Task” dropdown select “On a Schedule”
  3. Under Setting radio button choose “Daily” also choose the time at 10:00 PM (according to your wish).
  4. Don’t change advanced settings for now.


e) In the “Actions Tab
  1. Click “New” in the Actions Tab.
  2. In the “New Action” window ensure the “action” is set to Start a program.
  3. Under settings Program/Script write “Powershell.exe”
  4. In Add Arguments (optional) type &'d:\Backup-SiteCollections.ps1'. Note: Wrapping the file path and name in single quotation marks allows you to specify spaces in the text.


You should now see your script in the Task Scheduler Library (if not, click Refresh in the right-hand panel). To test the script, highlight it in the console and click Run from the right-hand panel.

Automated PowerShell Script to backup SharePoint Farm or Site Collection with email Notification

In today’s fast paced environment, we really like most of our things to be automated and at the same time get an alert on how things are going, so we can take necessary steps as required. Administering a SharePoint 2010 farm is no different, and as a day to day activity we have to take periodic backups of the entire farm or a particular Site Collection and at the same time be prepared for disaster recovery if required. I have prepared a small yet powerful PowerShell script for taking a backup of the entire SharePoint 2010 farm and at the same time notifying you via email the outcome of the Script i.e. Was the backup successful or did it fail and the reason why it failed.
Let’s Start
# NAME: SP2010_Farm_Backup_With_Notification.ps1
# AUTHOR: Kishor Kumar
# DATE: 07 December 2010
# COMMENT: A Powerful Script to take backup of the entire SharePoint 2010 Farm with email notification.
Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue
try
 {
  $today = (Get-Date -Format dd-MM-yyyy)
 #Location of the Backup Folder
  [IO.Directory]::CreateDirectory("E:\Backup\DailyFarmBackUp\$today")
 # This will actually initiate the SPFarm backup.
  Backup-SPFarm -Directory E:\Backup\DailyFarmBackup\$today -BackupMethod full
 # Edit the From Address as per your environment.
  $emailFrom = "SPADMIN@Sharepoint.com"
 # Edit the mail address to which the Notification should be sent.
  $emailTo = "Admin@SharePoint.Com"
 # Subject for the notification email. The + “$today” part will add the date in the subject.
  $subject = "The SharePoint Farm Backup was Successful for "+"$today"
 # Body or the notification email. The + “$today” part will add the date in the subject.
  $body = "The SharePoint Farm Backup was Successful for "+"$today"
  # IP address of your SMTP server. Make sure relay Is enabled for the SharePoint server on your SMTP server
  $smtpServer = "192.168.0.0"
  $smtp = new-object Net.Mail.SmtpClient($smtpServer)
  $smtp.Send($emailFrom, $emailTo, $subject, $body)
 }
Catch
 {
  $ErrorMessage = $_.Exception.Message
  # Configure the below parameters as per the above.
  $emailFrom = "SPADMIN@Sharepoint.com"
  $emailTo = "Admin@SharePoint.Com"
  $subject = "The SharePoint Farm Backup Job failed on "+"$today"
  $body = "The SharePoint Farm Backup Job failed on "+"$today and the reason for failure was $ErrorMessage."
  $smtpServer = "192.168.0.0"
  $smtp = new-object Net.Mail.SmtpClient($smtpServer)
  $smtp.Send($emailFrom, $emailTo, $subject, $body)
 }
A brief on the execution of the above script
  1. First it will get the current system Date in dd-MM-yyyy format [07-12-2010].
  2. It will create a folder with Current Date as the name in the following location E:\Backup\DailyFarmBackup\
  3. Next step will be to start SharePoint 2010 Farm backup procedure in the newly created folder.
  4. Once the backup is complete it will send a notification email to the email address mentioned in the $emailTo field.
  5. If the backup fails for some reason, you will receive an email containing the reason why the backup failed.
You can download the above script & the another one for backing up the Site Collection from the following locations
Rename the above files extension from .txt to .ps1
Note
  • Once you have configured the script as per your environment, create a new task in Task Scheduler for the above script and set it to run as per your requirement.
  • Make sure you periodically check the backup folder size as this script will not delete those for you.
  • Make sure you provide a valid From/To address and SMTP server IP address, validate these settings by checking with your Exchange Administrator if needed.
  • As I have mentioned before the script is very powerful, you can change the task to whatever you like to automate and get an email for failure or success for that particular task.
=========================================================================================
# NAME: SP2010_Site_Collection_Backup_With_Notification.ps1
# DATE: 07 December 2010
# COMMENT: A Powerful Script to take backup of the a particular Site Collection SharePoint 2010 Farm with email notification.
   # Website: http://thecommunicator.co.cc =========================================================================================
Add-PsSnapin Microsoft.SharePoint.Powershell –ErrorAction SilentlyContinue

try
 {
  $today = (Get-Date -Format dd-MM-yyyy)
 # Location of the Backup Folder
  [IO.Directory]::CreateDirectory("E:\Backup\DailySiteCollectionBackUp\$today")
 # Address of the Site Collection to backup
  $Site = "Site collection Address"
 # This will actually initiate the backup process.
  Backup-SPSite -Identity $Site -PathE:\Backup\DailySiteCollectionBackUp\$today
 # Edit the From Address as per your environment.
  $emailFrom = "SPADMIN@Sharepoint.com"
 # Edit the mail address to which the Notification should be sent.
  $emailTo = "Admin@SharePoint.Com"
 # Subject for the notification email. The "+“$today part will add the date in the subject.
  $subject = "The Site Collection "+"$Site  was backed up Successful on "+"$today"
 # Body or the notification email. The + “$today” part will add the date in the subject.
  $body = "The Site Collection "+"$Site was backed up Successful on "+"$today"
 # IP address of your SMTP server. Make sure relay Is enabled for the SharePoint server on your SMTP server
  $smtpServer = "192.168.0.0"
  $smtp = new-object Net.Mail.SmtpClient($smtpServer)
  $smtp.Send($emailFrom, $emailTo, $subject, $body)

 }

Catch
 {
  $ErrorMessage = $_.Exception.Message
 # Configure the below parameters as per the above.
  $emailFrom = "SPADMIN@Sharepoint.com"
  $emailTo = "Admin@SharePoint.Com"
  $subject = "The Site Collection "+"$Site backup failed on "+"$today"
  $body = "The Site Collection "+"$Site backup failed on "+"$today and the reason for failure was $ErrorMessage."
  $smtpServer = "192.168.0.0"
  $smtp = new-object Net.Mail.SmtpClient($smtpServer)
  $smtp.Send($emailFrom, $emailTo, $subject, $body)
 }


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-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:
Get-ExecutionPolicy
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 spaces 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'
$a=5
echo 'setting a value for a'
$b=3
echo 'adding a and b'
$c=$a+$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'
    }
    else
    {
        $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
 
$CurrentDir=$args[0]
$solutionName="Limeco.UI.WebParts.wsp"
$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'
WaitForJobToFinish 
 
Write-Host 'Going to remove solution'
Remove-SPSolution –entity $solutionName -confirm:$false
 
Write-Host 'Going to add solution'
Add-SPSolution $SolutionPath
 
Write-Host 'Going to install solution to all web applications'
Install-SPSolution –entity $solutionName –llwebapplications –ACDeployment
 
Write-Host 'Waiting for job to finish' 
WaitForJobToFinish 
 
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%)

Conclusion

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:

No comments:

Post a Comment