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 (6573) Trackbacks (0)
  1. When some one searches for his vital thing, therefore he/she needs to be available that
    in detail, so that thing is maintained over here.

  2. It’s an amazing post designed for all the internet people; they will obtain benefit from it
    I am sure.

  3. What’s Taking place i am new to this, I stumbled upon this I’ve found It
    positively helpful and it has aided me out loads.
    I hope to give a contribution & help different users like
    its helped me. Great job.

  4. Aw, this was a really nice post. Taking a few minutes and actual effort to make a very
    good article… but what can I say… I put things off a lot and never seem to get
    anything done.

  5. I do not know whether it’s just me or if perhaps everybody else experiencing problems with your site.
    It appears as if some of the written text on your posts
    are running off the screen. Can someone else please comment and let me know if this
    is happening to them too? This might be
    a issue with my internet browser because I’ve had this happen previously.
    Thank you

  6. It is not my first time to pay a quick visit this website, i am visiting this
    web site dailly and get nice information from here everyday.

  7. Hi, its pleasant paragraph regarding media print, we all understand media
    is a impressive source of data.

  8. Informes de situaciones que ocupa el sitio en los motores de búsqueda en función de las palabras clave elegidas.

  9. An outstanding share! I’ve just forwarded this onto a colleague who was doing a
    little research on this. And he actually ordered me breakfast because I discovered
    it for him… lol. So let me reword this….
    Thanks for the meal!! But yeah, thanks for spending some
    time to discuss this topic here on your web page.

  10. I really like reading through an article that will make people think.
    Also, thank you for allowing for me to comment!

  11. Marvelous, what a website it is! This blog presents useful facts to us, keep
    it up.

  12. Estive pesquisando sobre guia da monografia e realmente é
    pasmante objetivo desse utilitário e creio que preciso bastante dessa luz no interior de termo do túnel” porém ainda me
    restam poucas dúvidas acima de esses auxílios disponível de tcc.

  13. You ought to examine the Tutorial first as it exhibits you the fundamentals of the software
    program and you may shortly get information on what the software can do and
    the place to search out it.

  14. What i don’t realize is actually how you’re now not actually a lot more
    smartly-favored than you may be now. You’re so intelligent.
    You understand thus significantly in terms of this topic,
    made me in my opinion imagine it from a lot of numerous angles.

    Its like women and men aren’t interested except it is something
    to do with Girl gaga! Your individual stuffs excellent.
    All the time maintain it up!

  15. I don’t know if it’s just me or if perhaps everyone
    else experiencing problems with your site. It appears as if some of the written text within your posts are running off the screen. Can someone else please provide feedback and let me
    know if this is happening to them as well? This may be a problem
    with my internet browser because I’ve had this happen previously.
    Cheers

  16. Asking questions are really good thing if you are not understanding anything
    entirely, except this post offers pleasant understanding yet.

  17. Very shortly this site will be famous amid all blog people, due to it’s good content

  18. Nice post. I was checking continuously this blog and I am impressed!
    Extremely useful information specifically the ultimate part :
    ) I take care of such info much. I was seeking this particular information for
    a long time. Thanks and best of luck.

  19. After I initially left a comment I appear to have clicked the -Notify me when new
    comments are added- checkbox and from now on every time a comment
    is added I receive 4 emails with the same comment.
    Is there an easy method you can remove me from that service?
    Cheers!

  20. Great information. Lucky me I ran across your website by accident (stumbleupon).
    I’ve bookmarked it for later!

  21. I’ve read a few just right stuff here. Certainly worth bookmarking for revisiting.

    I wonder how a lot attempt you set to create one of these excellent informative website.

  22. Great items from you, man. I have take into accout your stuff previous to
    and you are just extremely great. I actually like what you’ve acquired here, certainly like what you’re stating and
    the way during which you say it. You make it enjoyable and you still take care of to
    keep it wise. I cant wait to learn far more from you.
    That is actually a tremendous website.

  23. Yes! Finally someone writes about Fight.

  24. Hello, i think that i noticed you visited my weblog so
    i came to go back the desire?.I am trying to to find things to improve my website!I assume its ok to use
    a few of your ideas!!


Leave a comment

No trackbacks yet.