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 (6166) Trackbacks (0)
  1. %If we’re planning to monetize our website or blog, the ads you see are the basis of monetization. Of course, official traffic or unique targeted visitors are imperative prosaic for our blog or website to generate cut besides impressions.

  2. %The list of leased cars given is as follows: best super mini cars namely Renault Clip and Twingo, Stylish cars namely Megane Coupe Cabriolet and Renault Wind come with hatchback, multi purpose vehicle called Renault Escape, famous models of Renault.

  3. While most people enjoyed the location by way of its net presence, Project Free TV was additionally a large hit with customers of Kodi/XBMC.

  4. %To move files from your computer to a hosting server so it appears on the internet, you need some software. There are various FTP Clients to choose from, some you pay for and others are free.

  5. %Recover iPod Files – iPod Recovery
    iPod is most popular and trendy device among the music lovers for its convenience to listen to songs anywhere and everywhere and to refresh yourself.

  6. %Nowadays, has become a flagship store in Wuhan
    Home Appliances
    Flagship store
    Label
    .

  7. %This car has been specially designed by Ford India to suit the family car section and is expected to give a stiff competition to Maruti Swift, Hyundai i10 and Toyota Etios Liva at a comparable price junction.

  8. %In the past, many people were easily able to trade in older vehicles for newer ones, making the number of older models available and still in good condition higher than it is today.

  9. %If you are a very busy person, you might not have enough time to play games, listen to music or download the best mobile games 2015 android apps, but you need an assistant to remind you of some important things, well there are free android apps.

  10. %Chrome Bar Stools are the exceedingly good at adding a hint of elegance to any room and the popularity of these bar stool is increasing at an impressive rate, they are extremely adaptable and blend in to any room.

  11. %If you wish to download Xbox 360 games for free, raise your hand. For the fifty or so dollars that it costs to buy one Xbox 360 game at retail, a smart gamer can get unlimited downloads for any of the Xbox games.

  12. %These applications are easy to use along with being very convenient for anyone. Lets get some more information about the types of features that are offered.

  13. %Liability practice is one and only of the most important factors or try to be wellness. Through exercises, we train our body to act upon plus to work normally. The result is our metabolism run the right way.

  14. Have you ever considered about adding a little bit more than just your articles?
    I mean, what you say is valuable and all. However think of
    if you added some great photos or video clips to give your posts more,
    “pop”! Your content is excellent but with images and video clips, this site could undeniably be one
    of the very best in its field. Wonderful blog!

  15. Hi, I think your website might be having browser compatibility issues.
    When I look at your website in Chrome, it looks fine but when opening
    in Internet Explorer, it has some overlapping. I just wanted to give you a quick
    heads up! Other then that, great blog!

  16. %Mobile and handled devices today are so affordable so anyone can buy one for their personal or business use. You can always check the internet for more options of devices that you can use for downloading the latest Android apps today.

  17. %Take your search further. Best Innovation in Google Innovation,On Tuesday morning, January 21, the world awoke to nine new words on the home page of Google Inc.

  18. A company that provides exceptional language translation service translates meaning and not words.
    Setting a date for a certain goal is also very helpful.
    Business letters are the primary means by which your company would
    communicate to investors.

  19. you are really a excellent webmaster. The website loading speed is
    incredible. It kind of feels that you’re doing any unique
    trick. In addition, The contents are masterpiece. you have performed
    a wonderful process in this matter!

  20. この歳になると、だんだんとシワが増えたと感じるようになりました。

    若いころの時点では分からなかったのですが、数年前でもそんな兆候はなかったのに、突然にシワが増えたのです。おばさんになったなと実感します。

    美容のCMって最近少なくないですが、ヒアルロン酸を試すなどケアって意識して注意しなければいけませんね。実年齢よりも老けて見えるなんて、ありえないですもん。

  21. Thousands of students take ATMA exam every time, it is conducted.
    Although the firm has the essay writers you can trust, it is also important to keep in touch so as to get updates about the progress made in writing your work and to make suggestion and add any new details that you would like to be considered
    at different writing stages. The bank’s move came after Hicks and Gillett tried
    to block the sale of the club to New England Sports Ventures by removing managing director Christian Purslow and commercial director Ian Ayre
    from the board.

  22. Rajeev Jain (Born: 1968, Lucknow) started working
    as a director of photography in 1993, after serving an apprenticeship as camera assistant and camera
    operator. Simple and short is always better, and unnecessary vocabulary or extraneous information should be deleted.
    This is the most key element in the approval of the research project.

  23. I do trust all the concepts you’ve introduced to your post.
    They are really convincing and will certainly work.

    Still, the posts are too quick for novices. May
    you please lengthen them a bit from subsequent time? Thanks for the post.

  24. Some of the best foods for men over 50 are foods high
    in omega-3 fatty acids for heart, prostate, and brain health.

  25. If you decide to download and install games to your laptop system
    after that it is advisable to be completely sure that the site doesn’t have any sort of kind of infections
    or else your computer system will get harmed.


Leave a comment

No trackbacks yet.