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 (7987) Trackbacks (0)
  1. Café verde: Es uno de los más potentes quemagrasas.

  2. What’s up, after reading this amazing post i am also cheerful to share my know-how here with colleagues.

  3. This post is truly a fastidious one it helps new the web users, who are wishing for blogging.

  4. You ought to take part in a contest for one of the best websites on the web.
    I am going to highly recommend this site!

  5. Appreciation to my father who informed me on the topic of this
    web site, this webpage is truly awesome.

  6. Hello, its pleasant paragraph concerning media print, we all be aware of media is a enormous source
    of information.

  7. Nice replies in return of this matter with real arguments and telling everything about that.

  8. The remote control includes 3 different frequencies, and you can operate the car from up
    to 8 meters. Be smart and savvy when negotiating the interest rate
    for new cars and don’t just sign on the bottom line. 00 per gallon, depending on market prices,
    but that is a good benchmark.

  9. A new technology introduced by one of the biggest automobile companies, Volvo,
    will ensure that your car avoid accidents on the roads involving pedestrians.
    So, you are not required to move from one dealer to another for ideal model.
    Listed here are some interesting facts about Mercedes-Benz.

  10. Greetings I am so glad I found your site, I really found you by
    accident, while I was researching on Askjeeve for something else, Regardless I am here now and would just like
    to say cheers for a marvelous post and a all round exciting
    blog (I also love the theme/design), I don’t
    have time to read through it all at the minute but I have bookmarked
    it and also added your RSS feeds, so when I have time I will
    be back to read much more, Please do keep up the awesome job.

  11. Believe me, I went from being a night to a morning and the
    only reason I discovered this website is since I
    was searching for any individual else that found they cannot do without an early morning shower.
    showers|showers Benadryl and various other antihistamines would
    create an evening horror every time, regardless of doctor’s tips that they would have the contrary result.

  12. Right now it appears like Movable Type is the best blogging platform available right
    now. (from what I’ve read) Is that what you’re using
    on your blog?

  13. Believe me, I went from being a night to a morning and also the only reason I found this site is since I was looking for
    anybody else who found they can not go without a morning shower.
    showers|showers Various other night sweats signs and symptoms consist
    of nausea, chills and just as in the case of warm flashes signs and symptoms,
    uneven heart beat.

  14. It’s in reality a nice and useful piece of info. I’m happy that you simply shared this useful
    info with us. Please stay us up to date like this. Thank you for sharing.

  15. I relish, lead to I found just what I was taking a look for.
    You’ve ended my four day lengthy hunt! God Bless you man. Have a great day.


  16. If some one wants to be updated with hottest technologies therefore he must be pay a visit this site and be up to date all the time.

  17. Appreciation to my father who shared with me concerning this
    blog, this website is truly awesome.

  18. It’s impressive that you are getting ideas from this piece of writing as
    well as from our dialogue made here.

  19. I have read so many content about the blogger lovers except
    this post is truly a pleasant piece of writing, keep it up.

  20. Thank you a bunch for sharing this with all people you actually recognise what you are speaking approximately!
    Bookmarked. Kindly additionally visit my website =). We can have a hyperlink change
    agreement between us

  21. It is far simpler to use on-line hack tool for conflict royale game and the very best factor
    to know is that this generator can fulfill your requirement of unlimited in game
    currencies within jiffy.

  22. I see you don’t monetize your website, don’t waste your traffic, you can earn extra cash every month because you’ve got high quality content.
    If you want to know how to make extra $$$, search for: best adsense alternative Dracko’s tricks

  23. A fascinating discussion is definitely worth comment.
    There’s no doubt that that you ought to publish more
    about this topic, it might not be a taboo subject but usually people don’t speak
    about these topics. To the next! Cheers!!

  24. The region has seen its own building increase in recent years, which, when coupled
    with broader economic challenges, has dampened hotel performance.

  25. The broad spectrum of dances includes contemporary, classical, ballroom, street,
    jazz, hip-hop, musical theatre as well as their sub-genres.

    As the first part of thhe Lyrics break, it is obvious that
    she is tattling in redgards to a past kinship (. In this Shahrukh Khan hass played role just as
    the one played in Super Hero.

  26. If placed in the center of the property, it promotes good health and communication.
    You needn’t be worried about the expenditure
    as there are many offers and discounts to appeal to your
    needs. To make this possible, have a plant that is situated every eight to ten feet.

  27. I know this site gives quality dependent articles or reviews and extra data, is there any other web
    site which offers such stuff in quality?

  28. Actually, common testing is very really helpful.

Leave a comment

No trackbacks yet.