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 (5713) Trackbacks (0)
  1. Hi there friends, how is everything, and what you wish for to say concerning
    this piece of writing, in my view its truly remarkable for me.

  2. I believe what you said was very reasonable. However, what about
    this? what if you added a little information? I am not saying your information is not solid,
    but what if you added something that makes people desire more?
    I mean How to backup SharePoint using PowerShell «
    Olav Aukan is a little boring. You should look at Yahoo’s front
    page and see how they create post titles to grab people interested.

    You might add a related video or a related picture or two to get people excited about everything’ve written. Just my opinion, it would bring your posts a little
    bit more interesting.

  3. Thanks for your personal marvelous posting!
    I seriously enjoyed reading it, you can be a great author.I will be sure to bookmark your blog and will eventually come back sometime soon.
    I want to encourage you to definitely continue your great work, have
    a nice morning!

  4. Online gambling establishment free play no deposit would certainly be astonishing if there were limitations on doing that.

  5. Remarkable! Its truly awesome paragraph,
    I have got much clear idea about from this
    article.

  6. You might be penalizeded, locked up for approximately 2 years or both if you carelessly or deliberately provide equipments.

  7. Hi exceptional website! Does running a blog similar to this take a great deal of work?
    I have absolutely no expertise in coding but
    I was hoping to start my own blog soon. Anyway, should you have
    any recommendations or tips for new blog owners please share.
    I know this is off subject but I simply needed to
    ask. Thanks!

  8. Play for an edge or play for fun – every video game is
    an absolutely exact depiction of a few of the most preferred video slots of
    perpetuity.

  9. Right here’s a large list of possibilities I created for earning income online for you all.

  10. Lastly, make confident your possible lawyer is somebody you can trust and has shown trustworthy behavior
    throughout their profession.

  11. I rarely drop responses, however i did a few searching and wound up here How to backup SharePoint
    using PowerShell « Olav Aukan. And I actually do have some questions for you if you usually
    do not mind. Could it be only me or does it appear like a few of the remarks come
    across like they are left by brain dead visitors?
    :-P And, if you are posting at additional social
    sites, I’d like to keep up with anything fresh you have to post.
    Would you make a list of the complete urls of your communal pages like your twitter feed, Facebook page or linkedin profile?

  12. Hello mates, how is all, and what you would like to say concerning this article, in my view its truly awesome designed for me.

  13. It’s in point of fact a nice and helpful piece of information. I am glad that you just shared this useful information with us.
    Please stay us informed like this. Thank you for sharing.

  14. In today’s time, the success that are awarded on port video games go
    to as high as millions!

  15. excellent submit, very informative. I wonder why the other specialists of this sector do not notice this.
    You should continue your writing. I am confident, you have a great readers’ base already!

  16. As an example, a mob of by-standers could really
    feel entitled to a round of free beverages at the bar – on you.

  17. Attorney Rothenberg has also received the prime score of 10 from AVVO for
    a Best Private Injury Lawyer.

  18. You could find lots of details about different coin machine, along with individuals which will certainly have
    these collector items offer for sale.

  19. This paragraph will help the internet users for creating new web site or even a blog from
    start to end.

  20. I’m now not sure where you are getting your information, however
    good topic. I must spend some time learning much more or understanding more.
    Thank you for magnificent information I was on the lookout for this info for
    my mission.

  21. In 1991, Attorney Jahrmarkt received his Juris Doctor degree in Law from Yeshiva University, Benjamin N.
    Cardozo College of Law.

  22. Whether a back injury, whiplash injury or any other healthcare issue, if this is
    a consequence of an accident caused by one more particular person/organization’s
    error, our group will help you to claim against all your losses.

  23. Great weblog right here! Also your site quite a bit
    up fast! What host are you using? Can I am getting your affiliate hyperlink
    to your host? I want my site loaded up as fast as yours lol

  24. My brother recommended I might like this web site.
    He used to be totally right. This publish actually made my day.
    You can not consider simply how a lot time I had spent for this information! Thanks!

  25. Hello there Precious Quite Gorgeous Post To A lot better Tips To Creat Effective Blog Thanks For Of All Your
    Article Really Close My Heart Because I Am Daily Site visitor Of Your
    Site And Obtaining More Expertise From Here.

  26. Any underlying problem that affects the glands that produce testosterone and other hormones is the leading low sperm count causes.
    Men with low levels of testosterone exhibited a greater ability to
    manufacture antibodies against diseases. HAWTHORN BERRY –
    The hawthorn berry is another herb that is generally used to treat one concern, yet
    its benefits extend further.

  27. All you have to do is get on your phone and dial among the local 24-hour
    vehicle locksmith professional services.

  28. Search Engine Optimization especially aids in optimization for Ecommerce
    websites that are based on content management systems, osCommerce, php Shop, Zen Cart as
    well as ASP based.

  29. The charge for working with a locksmith will vary depending on the specific locksmith professional, the locksmith business,
    and the particular job being done.

  30. Yes! Finally something about testosterone booster.

  31. 昔はCMで大流行した無人契約機を使用して、申込みするという簡単な方法だってよく使われています。無人機を相手に自ら新規申込みを行うので、決して誰にもばれずに、急な出費があったときなどにカードローン申込をひっそりとすることができるので心配はありません。
    いわゆる貸金業関連の情報が検索できるポータルサイトをうまく活用すれば、スピーディな即日融資ができる消費者金融業者(いわゆるサラ金)を、家のPCから検索することも融資を申し込むことも問題ないのです。
    銀行カードローンは、通常の借入よりも年利が安いという特長があります。審査をした時の基準で、しっかり毎月の収入のある人のみがキャッシングをすることができますがパートタイマーや派遣社員の方もキャッシングができるようです。

  32. Nice post. I was checking constantly this blog and I’m impressed!
    Very helpful information particularly the last part :) I care for such info much.

    I was seeking this certain information for a very long time.
    Thank you and good luck.

  33. This site was… how do you say it? Relevant!! Finally I have found something which helped me.
    Cheers!

  34. Do you mind if I quote a couple of your posts as long as I provide credit and sources back to your blog?
    My blog is in the very same niche as yours and my users would certainly benefit from a lot of the information you present here.
    Please let me know if this okay with you. Cheers!

  35. First of all I want to say awesome blog! I had a
    quick question that I’d like to ask if you don’t mind.
    I was curious to know how you center yourself and clear your
    head prior to writing. I have had a tough time clearing my thoughts in getting my
    thoughts out there. I do take pleasure in writing but it just seems like the first 10 to
    15 minutes are lost just trying to figure out how to begin. Any recommendations
    or hints? Cheers!

  36. Wonderful article! We are linking to this great post on our site.
    Keep up the good writing.


Leave a comment

No trackbacks yet.