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 (7451) Trackbacks (0)
  1. An interesting discussion is worth comment. There’s no doubt
    that that you need to write more about this topic, it may not be
    a taboo subject but usually folks don’t talk
    about these topics. To the next! All the best!!

  2. A new technology introduced by one of the biggest automobile companies, Volvo,
    will ensure that your car avoid accidents on the roads involving pedestrians.
    All since then, Indica is floating in the market with a regular
    sale. Listed here are some interesting facts about Mercedes-Benz.

  3. The proceeds of selling your older car can go
    to the operations of the charity like giving food
    or clothing to the family that they supported. Strict standards and excellence in service is what made Cullitons the premiere limo service of
    choice for thousands of Torontonians as well as visiting guests from all over the
    world. The damage varies from vehicle to vehicle but can be as small as light hail damage which is barely visible through
    to damage caused by falling trees.

  4. The proceeds of selling your older car can go to the operations of the charity like giving food or clothing to the family that they
    supported. Today, Parents magazine and car-buying platform Edmunds.
    Listed here are some interesting facts about Mercedes-Benz.

  5. Along with the car sales, the Japanese used car sellers
    also supply the dismantled parts of the vehicles
    in cube containers of size 20ft or 40 ft.
    Now you will soon forget about key-fobs as well since new biometric revolution is going to allow you to enter
    your car with your fingerprint, face detection or eyeball recognition. Go to the search tool and search for
    keyword like used cars in Bangalore, pre owned cars and second hand cars in Bangalore.

  6. So you, as the restorer, have to set realistic
    goals as to exactly what parts of the car you
    are going to restore to their original states and what parts of
    the car you are willing to restore “as close as possible” to their original states.
    Producing a very light car will drop its fuel consumption,
    and oil companies will not appreciate this. Go to the
    search tool and search for keyword like used cars in Bangalore,
    pre owned cars and second hand cars in Bangalore.

  7. Costs there can be as minimal as $500 for your automobile in a excellent situation. All since then, Indica is floating in the market with a regular sale.
    The damage varies from vehicle to vehicle but can be as small as light hail damage which is barely visible through to damage caused by falling trees.

  8. Costs there can be as minimal as $500 for your automobile in a excellent
    situation. Today, Parents magazine and car-buying platform Edmunds.
    Access Free Online Maps via Wi – Fi or 3G network, such as Google Map.

  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. Today, Parents magazine and car-buying platform Edmunds.
    Access Free Online Maps via Wi – Fi or 3G network, such as
    Google Map.

  10. great. You save my day. Thanks for sharing.

  11. Asking questions are actually nice thing if you are not understanding
    something completely, but this piece of writing provides pleasant understanding yet.

  12. A new technology introduced by one of the biggest automobile
    companies, Volvo, will ensure that your car avoid accidents
    on the roads involving pedestrians. Producing a very light car will drop its fuel consumption, and oil companies will not appreciate
    this. The damage varies from vehicle to vehicle but can be as small as light hail damage which is barely visible through to damage caused by falling trees.

  13. Our latest addition to the limousine fleet is the 7 passenger Cadillac Escalade.
    So, you are not required to move from one dealer to another for ideal
    model. 00 per gallon, depending on market prices, but that is a
    good benchmark.

  14. Along with the car sales, the Japanese used car sellers also supply
    the dismantled parts of the vehicles in cube containers of size 20ft or 40 ft.

    Once you do that take a spray bottle filled with 4 cups of warm water and a
    tablespoon of detergent and spray the stain. According to Campbell Fuller, spokesman for the ICA, buyers
    need to contact their insurer before agreeing to a purchase.

  15. Costs there can be as minimal as $500 for your automobile in a excellent situation.
    Today, Parents magazine and car-buying platform Edmunds. It is available in two versions of petrol and diesel and has been a very
    reasonable price.

  16. The proceeds of selling your older car can go to the operations of the
    charity like giving food or clothing to the family that they supported.
    The turbo 4-banger in the Volkswagon GTI Mk5 is fairly unique
    among such engines in that it produces huge amounts of torque at a relatively low number
    of RPMs. 00 per gallon, depending on market prices,
    but that is a good benchmark.

  17. You are so interesting! I do not suppose I’ve truly read through a single thing like
    this before. So nice to discover somebody with
    some unique thoughts on this subject matter.
    Really.. thank you for starting this up. This web site is one thing that is needed on the web, someone with some
    originality!

  18. Hello it’s me, I am also visiting this web site daily, this website is truly good and
    the users are genuinely sharing good thoughts.

  19. I do agree with all of the concepts you’ve offered on your post.

    They’re really convincing and can certainly work. Still, the posts
    are very short for newbies. May you please prolong them a bit from next time?
    Thanks for the post.

  20. Oh my goodness! Incredible article dude! Thank you, However
    I am experiencing problems with your RSS.
    I don’t understand the reason why I cannot join it. Is
    there anybody else getting the same RSS issues? Anybody who knows the answer can you kindly respond?
    Thanx!!


Leave a comment

No trackbacks yet.