Olav Aukan Getting information off the Internet is like taking a drink from a fire hydrant…


How to backup SharePoint using PowerShell

Lately I've been reading up on - and experimenting with - PowerShell to automate alot of the tings I do in SharePoint. The original motivation was a deployment gone bad (ie. too many manual steps + too little time = too many errors) and it got me rethinking my whole approach to managing SharePoint.

My previous attempts at automating the build -> package -> deploy process with a .bat file calling MSBuild and STSADM commands had failed miserably about two years ago. It would not wait for the solution to finish retracting before trying to remove it, or it would try to activate a feature before the solution was finished deploying, etc. Also, since it was one giant monolithic script, any errors early on in the process would cause all sorts of problems.

There are ways to deal with this in .bat files, but they don't even come close to the cool stuff you can do with PowerShell! Therefore I'm planning on writing a couple of posts about using PowerShell to manage SharePoint based on the things I've been trying out so far. Keep in mind that I'm still learning and some of the stuff I write about might be stupid, inefficient or downright wrong. With that disclaimer out of the way I present my first PowerShell script: Performing a full farm backup.

# This function performs a complete backup of the local farm
function SP-Backup-Farm {

	param (
		[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]

	process {

		Write-Host "Attempting full backup of the farm."

		# Create the backup settings
		$Settings = [Microsoft.SharePoint.Administration.Backup.SPBackupRestoreSettings]::GetBackupSettings($BackupFolder, "Full");

		# Set optional operation parameters
		$Settings.IsVerbose = $true;
		$Settings.UpdateProgress = 10;
		$Settings.BackupThreads = 10;

		# File size details
		$BackupSize = New-Object UInt64
		$DiskSize = New-Object UInt64
		$DiskFreeSize = New-Object UInt64

		Write-Host "Backup Location:" $BackupFolder

		# Check that the target folder exists
		if (Test-Path $BackupFolder)
			Write-Host "Backup Location Exists: True"

			# Backup operation details
			$BackupID = [Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::CreateBackupRestore($Settings);
			$BackupObjects = [Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::FindItems($BackupID, "Farm");

			# Get file size info
			$BackupSize = [Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::DiskSizeRequired($BackupID)
			[void][Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::DiskSize($BackupFolder, [ref]$DiskFreeSize, [ref]$DiskSize)

			# Check if there is enough free disk space
			$HasEnoughSpace = $false
			if ($DiskFreeSize -gt $BackupSize)
				$HasEnoughSpace = $true

			$BackupSizeString = Util-Convert-FileSizeToString $BackupSize
			$DiskSizeString = Util-Convert-FileSizeToString $DiskSize
			$DiskFreeSizeString = Util-Convert-FileSizeToString $DiskFreeSize

			Write-Host "Total Disk Space:" $DiskSizeString
			Write-Host "Free Disk Space:" $DiskFreeSizeString
			Write-Host "Required Disk Space:" $BackupSizeString

				Write-Host "Sufficient Free Disk Space: True"

				# Set the backup as the active job and run it
				if ([Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::SetActive($BackupID))
					$BackupObjectCount = $BackupObjects.Count

					Write-Host "Successfully set backup job as the active job."
					Write-Host "Backup consists of $BackupObjectCount object(s)"
					Write-Host "Backup Started"

					foreach($BackupObject in $BackupObjects)
						if (([Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::Run($BackupID, $BackupObject)))
							Write-Host "Backup Completed"
							Write-host "An unexpected error occured!" -ForegroundColor Yellow
							Write-Host "Backup Failed" -ForegroundColor Yellow
					Write-Host "Unable to set backup job as the active job." -ForegroundColor Yellow
					Write-Host "Backup Failed." -ForegroundColor Yellow
				Write-Host "Sufficient Free Disk Space: False" -ForegroundColor Yellow
				Write-Host "Backup Failed" -ForegroundColor Yellow
			Write-Host "Backup Location Exists: False" -ForegroundColor Yellow
			Write-Host "Backup folder doesn't exist or the service account does not have read/write access to it." -ForegroundColor Yellow
			Write-Host "Backup Failed." -ForegroundColor Yellow


		# Clean up the operation
		if (!$BackupID -eq $null)

# This function returns a "user friendly" display value for a filesize in bytes
function Util-Convert-FileSizeToString {

    param (
		[Parameter(Mandatory=$true, ValueFromPipeline=$true, Position=0)]

    switch ($sizeInBytes)
        {$sizeInBytes -ge 1TB} {"{0:n$sigDigits}" -f ($sizeInBytes/1TB) + " TB" ; break}
        {$sizeInBytes -ge 1GB} {"{0:n$sigDigits}" -f ($sizeInBytes/1GB) + " GB" ; break}
        {$sizeInBytes -ge 1MB} {"{0:n$sigDigits}" -f ($sizeInBytes/1MB) + " MB" ; break}
        {$sizeInBytes -ge 1KB} {"{0:n$sigDigits}" -f ($sizeInBytes/1KB) + " KB" ; break}
        Default { "{0:n$sigDigits}" -f $sizeInBytes + " Bytes" }

The convert bytes to string function was something I found on another blog and adapted to PowerShell, so I can't really take credit for that one. Also it took about 3 hours to do a full backup on my VMWare machine with about 50GB of content databases. Your milage may vary...

Comments (8186) Trackbacks (0)
  1. wonderful issues altogether, you simply won a new reader. What could you suggest in regards to your post that you simply made a few days ago? Any positive?

  2. There are actually loads of particulars like that to take into consideration. That could be a nice level to carry up. I provide the thoughts above as normal inspiration but clearly there are questions like the one you convey up the place crucial thing will be working in sincere good faith. I don?t know if greatest practices have emerged round things like that, but I am positive that your job is clearly identified as a fair game. Each boys and girls really feel the impact of just a momentpleasure, for the rest of their lives.

  3. Więcej informacji w Polityce Prywatności.

  4. 4 – Batata doce melhora desempenho sexual.

  5. Hi there friends, how is the whole thing, and
    what you would like to say about this paragraph, in my
    view its actually remarkable designed for me.

  6. Thanks for sharing your thoughts about video production editing.

  7. According to research specialists from Research2guidance, there are an estimated 97,
    000 fitnesss and weight reduction apps out there.

  8. Greetings I am so glad I found your webpage, I really found you by error, while I was
    searching on Aol for something else, Regardless I am here
    now and would just like to say thanks a lot for a tremendous post and a all round thrilling blog (I also love the theme/design), I don’t have time to go
    through it all at the minute but I have bookmarked it
    and also added in your RSS feeds, so when I have time I will be back to read more,
    Please do keep up the great job.

  9. I’m impressed, I must say. Rarely do I encounter a blog that’s equally
    educative and interesting, and let me tell
    you, you’ve hit the nail on the head. The problem is something not enough men and women are speaking intelligently about.
    Now i’m very happy that I stumbled across this during my hunt for something regarding this.

  10. I am no longer positive the place you are getting your info, but great
    topic. I must spend some time learning more or figuring out more.

    Thanks for fantastic information I was looking for this info for my mission.

  11. Like all fields, photography, professional photography at this, just isn’t as easy as one could think.
    As the first area of the Lyrics break, no doubt that they is tattling with regards to
    a past kinship (. In this Shahrukh Khan has
    played rile just as the one played in Super Hero.

  12. I quite like reading a post that will make men and
    women think. Also, thanks for allowing for me to comment!

  13. Si no ha ido tan bien y tu página esta penalizada, los consejos de este guía pasito a
    pasito te ayudarán a recuperar el posicionamiento
    en Google de tu página.

  14. The broad spectrum of danjces includes contemporary,
    classical, ballroom, street, jazz, hip-hop, musical theatre and every one of their sub-genres.
    Flowers appear in a selection of colors, and if you
    add steems and vines, you can get a wonderful custom
    tattoo design. But for guys like Colin Farrell or David
    Beckam , a negative boy look can better be achieved with a shaved head.

  15. It sticks out since it really went against my thinking initially when I had read it.
    Sometimes he complains that his eyes are tired with his
    fantastic shoulder pains. You may have a very habit of being really honest and
    you think vid sought after trait – who’s is, however when you are looking at your dates it is possible to
    really hurt their feelings if you’re too blunt and honest.

  16. I’m gone to convey my little brother, thaat he should also visit
    this weblog on regular basis to obtain updated from latest news update.

  17. It’s amazing to pay a visit this website and reading the views
    of all colleagues about this piece of writing, while I am also eager of getting familiarity.

  18. very good post, i definitely adore this amazing site, persist with it

  19. The accuracy of collected information cann be fluctuate as a result of the calculations are
    based on generic values for age, height, weight aand intercourse.

  20. Thanks for this grand post, I am glad I detected this internet site on yahoo.

  21. Humana People to People creates their objective to improve under-developed countries with offering instruction to
    primary school tutors and tradesmen, making an effort to
    promote well being and send knowledge of Aids and to help in extra increasing
    the areas farming. Humana People to People runs a variety of
    different plans and missions within poverty-stricken regions of countries all over the world.

    By way of working together with the local individuals and governing administration, they’re able
    to assist those people who are in need of funds thru their
    non-profit help corporations. China is among many nations that this non-profit institution comes to encounter the pressing
    concerns which they experience at present.
    The Humana People to People Activity works with The Federation for Associations from
    the Yunnan province of China. This work first commenced in 2005 and moves on throughout currently.
    The Humana People to People Cooperation Work Office from
    the Yunnan Area works to boost funds in an effort to achieve different jobs in the area around poverty-stricken areas.
    Several projects that Humana People to People seeks to bring to the current section of China
    include business schools in which they are able to advance their education,
    planning them to get employment, supplying details of transmittable illnesses and more.

  22. Very efficiently written information. It will be beneficial to everyone who employess it, including myself. Keep up the good work for sure i will check out more posts. bakedffeeaae

  23. Status Asthmaticus is a severe asthmatic attack that lasts long and results in pain. Asthmatic attack can’t be treated with normal drugs.
    Status Asthmaticus has similar symptoms like asthma but asthmatic inhalers won’t work for it.
    Possible respiratory failure is the main cause of acute severe
    asthma. Acute severe asthma is a critical situation and without immediate treatment
    it can lead to death. Find Out More: What are the causes of status asthmaticus?

  24. WOW just what I was searching for. Came here by searching for louis vuitton trunk

  25. Great weblog right here! Additionally your web site rather a lot upp verey fast!
    What host are you thee usage of?Can I geet your associate hyperlink
    in your host? I wish my wweb site loaded up as quickly as yours lol
    kereta api gumarang kkelas eksekutif

  26. 5 game mode continues to be substantially enhanced with
    respect to the previous Grand Theft Auto games.

  27. somtimes i also sell stuffs on craigslists because there are many users in it’

  28. I will immediately snatch your rss feed aas I
    can not find your e-mail subscription hyperlink or newsletter service.
    Do yoou have any? Please let me understand so that I may
    subscribe. Thanks.

Leave a comment

No trackbacks yet.