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
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
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 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 basisa) 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
d) In the “Triggers Tab”
e) In the “Actions Tab”
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) }
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
=========================================================================================
#
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)
}
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:
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.
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.
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"
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 likePowerShell 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.PowerShellFile: 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