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

21Mar/11

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)]
		[string]
		$BackupFolder
	)

	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"
			Write-Host

			# 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

			if($HasEnoughSpace)
			{
				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
					Write-Host "Backup Started"
					Write-Host

					foreach($BackupObject in $BackupObjects)
					{
						if (([Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::Run($BackupID, $BackupObject)))
						{
							Write-Host "Backup Completed"
						}
						else
						{
							Write-host "An unexpected error occured!" -ForegroundColor Yellow
							Write-Host "Backup Failed" -ForegroundColor Yellow
						}
					}
				}
				else
				{
					Write-Host "Unable to set backup job as the active job." -ForegroundColor Yellow
					Write-Host "Backup Failed." -ForegroundColor Yellow
				}
			}
			else
			{
				Write-Host "Sufficient Free Disk Space: False" -ForegroundColor Yellow
				Write-Host "Backup Failed" -ForegroundColor Yellow
			}
		}
		else
		{
			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
		}

		Write-Host

		# Clean up the operation
		if (!$BackupID -eq $null)
		{
			[void][Microsoft.SharePoint.Administration.Backup.SPBackupRestoreConsole]::Remove($BackupID)
		}
	}
}

# 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)]
		[int64]
		$sizeInBytes
	)

    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 (6380) Trackbacks (0)
  1. Hurrah! After all I got a webpage from where I be able to
    genuinely take valuable information regarding my study and knowledge.

  2. This post gives clear idea designed for the new visitors of blogging, that actually how to
    do running a blog.

  3. Hi there, I would like to subscribe for this web site to take most
    recent updates, thus where can i do it please assist.

  4. Is not it terrific whenever you locate a great article? indeed, study is paying off. Truly helpful mindset, appreciate your expression.. My personal web browsings seem complete.. thank you.

  5. This is a great tip especially to those fresh to the blogosphere.
    Short but very precise info… Appreciate your sharing this one.
    A must read post!

  6. I have learn several good stuff here. Certainly price bookmarking for revisiting.
    I surprise how so much effort you place to create such a fantastic
    informative website.

  7. My developer is trying to persuade me to move to .net from PHP.

    I have always disliked the idea because of the expenses.
    But he’s tryiong none the less. I’ve been using WordPress on several websites
    for about a year and am worried about switching to another platform.
    I have heard fantastic things about blogengine.net.
    Is there a way I can transfer all my wordpress posts into it?
    Any kind of help would be greatly appreciated!

  8. I blog frequently and I genuinely thank you for your content.
    This article has really peaked my interest. I’m going to book mark your blog and keep
    checking for new details about once a week.
    I opted in for your Feed as well.

  9. Hello to all, the contents existing at this web site are
    truly remarkable for people experience, well, keep up the good work fellows.

  10. This is one of the main factors that separate the online game from its land
    based counterpart. While most of these are not for money but the
    prizes can range form a toaster to a cruise. Reputable sites having online slot
    machines provide a secure line.

  11. of course like your web site but yyou have to test
    the spelling on several of your posts. Manyy of
    them are rife with spelling problems and I in finding it very
    bothersome to tell tthe trjth on thee other hand I’ll surely come back again.

  12. If you desire to obtain much from this piece of writing then you have to apply these strategies to your won webpage.

  13. 手汗をかいてしまうのは好きな人の前だったり初対面の人と話したり、あがっているからですよね。こういうのを精神性発汗というのですが、この汗は努力してどうにかなるものではありません。がんばって汗をかかないようにしよう、アガらないようにしようというのは不可能だからです。汗は文字通り汗腺(かんせん)というところから出ています。この汗腺に物理的にフタをして汗を出ないようにするというのが掌の汗を抑える有効な対策になります。このような作用は、しゅうれん作用といいます。もっともお手軽に手汗を抑える方法としてデオドラントを使う方法があります。ファリネという手汗専用の制汗パウダーや、フレナーラという手汗対策用の制汗ジェルクリームなどが人気です。

  14. You really make it appear really easy together with your presentation but I find this matter to be actually something that I feel I might never understand. It sort of feels too complex and extremely broad for me. I am taking a look forward to your next put up, I will try to get the hang of it!

  15. Thanks a lot for sharing this with all people you
    really recognise what you are talking about! Bookmarked.
    Please additionally visit my site =). We could have a hyperlink change arrangement between us

  16. Wonderful, what a website it is! Thanks for providing the information with this post. Post is very nice! By the way, I want to share with you information about the best.

  17. I loved as much as you will receive carried out right here.

    The sketch is attractive, your authored subject matter stylish.
    nonetheless, you command get bought an shakiness over that you wish be delivering the following.
    unwell unquestionably come further formerly again since
    exactly the same nearly a lot often inside case you shield this increase.

  18. Very nice post. I definitely love this site.

    Keep it up!

  19. Hello, after reading this remarkable paragraph i am as well
    cheerful to share my familiarity here with friends.

  20. Everything is very open with a clear description of the issues.
    It was really informative. Your website is very helpful.
    Thank you for sharing!

  21. certainly like your website however you have to test the spelling on quite a
    few of your posts. Several of them are rife with spelling
    problems and I in finding it very troublesome to tell the reality on the other hand I will definitely come back again.

  22. They can also provide you the total security systems installation for your residential or
    commercial purposes. It’s possible you’ll even search for evaluations online.
    In certain emergency situations, the availability of an expert
    locksmith in Delta BC is really helpful for the users.

  23. Thank you, I have just been searching for information about this topic for
    a while and yours is the greatest I’ve came upon till now.
    However, what in regards to the bottom line?
    Are you sure concerning the source?

  24. My coder is trying to convince me to move to .net from PHP.
    I have always disliked the idea because of the costs.
    But he’s tryiong none the less. I’ve been using WordPress on a number of websites for about a year and am anxious about switching to another platform.
    I have heard good things about blogengine.net.

    Is there a way I can transfer all my wordpress posts into it?
    Any kind of help would be really appreciated!

  25. I am really loving the theme/design of your site. Do you ever
    run into any browser compatibility problems? A number of my blog audience have complained about my blog not operating correctly
    in Explorer but looks great in Safari. Do you have any solutions
    to help fix this problem?

  26. It’s an awesome article in support of all the internet users; they will get
    benefit from it I am sure.

  27. naturally like your web site however you need to take a look at the
    spelling on quite a few of your posts. Several of them are rife with spelling issues and I to find it very bothersome to
    tell the reality nevertheless I’ll certainly come again again.

  28. Oh my goodness! Incredible article dude! Thank you so much, However I am encountering troubles with your RSS.
    I don’t understand why I can’t join it. Is there anyone else getting identical RSS issues?
    Anyone that knows the answer will you kindly respond?
    Thanks!!

  29. I’ve been exploring for a little bit for any high quality articles or blog posts on this kind of area .
    Exploring in Yahoo I ultimately stumbled upon this web site.
    Studying this info So i am happy to show that I
    have a very just right uncanny feeling I found out exactly what I needed.
    I most definitely will make sure to don?t overlook this
    website and provides it a look on a relentless basis.

  30. All you need to do is to eat balanced and healthy meals,
    so that you are going to get what you need. It will help to effectively
    use oxygen to aid in brain function, tissue repair, and skin regeneration. The deficiency of thiamine can lead to problems such as acute mood swings and lethargy.

  31. Hello there! This post couldn’t bee written any better!
    Reading this post reminds me of my previous room mate!
    He always kept chatting about this. I will forward this post to him.
    Pretty sure he will have a good read. Thanks ffor sharing!

  32. Aw, this was a very good post. Finding the time and
    actual effort to generate a great article…
    but what can I say… I put things off a whole lot and don’t seem to get
    anything done.

  33. Τhis paragraph wiⅼl assist the internet viѕitors for building
    up new blog or even a blog from start to end.

  34. Great site. Lots of helpful info here. I am sending it to several friends
    ans additionally sharing in delicious. And certainly,
    thank you on your sweat!

  35. It’s enormous that you are getting thoughts from this piece
    of writing as well as from our discussion made here.

  36. Como hemos visto, normalmente, cuanto más acolchados más calor generará
    un portabebés.

  37. Thanks for the marvelous posting! I actually enjoyed reading
    it, you are a great author. I will make certain to bookmark your blog and will eventually come back
    in the future. I want to encourage you to continue your great writing, have a nice weekend!


Leave a comment

No trackbacks yet.