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 (7725) Trackbacks (0)
  1. The warranties for some branded cars may go up to 3 or
    4 years depending on the model. 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.

  2. 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.
    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. Listed here are some interesting facts
    about Mercedes-Benz.

  3. Have you ever thought about creating an ebook or guest authoring on other sites?
    I have a blog based upon on the same topics you discuss and would love to have you share
    some stories/information. I know my subscribers
    would value your work. If you are even remotely interested,
    feel free to shoot me an email.

  4. Tremendous things here. I amm very satisfied to peer your article.
    Thank you so much and Iam having a look ahead to contact you.
    Will you please drop me a mail?

  5. ᖴirst offf Ⅰ would likе to ssay ǥreat blog! I ɦad
    a quick question in ᴡhich I’d likе to aѕk iff ʏou
    don’t mind. Ӏ was curious to ҝnow Һow yߋu center ʏourself and clear yoսr ind before writing.
    Ι’ve hhad trouble clearing mу mind in getting my thoughts out thеre.
    I truly do enjoy writing but іt just seemѕ liҝe the first 10
    to 15 minutes aree wasted simply ϳust tгying tto
    figure оut how to beɡin. Any ideas οr tips?

    Thank yoᥙ!

  6. It is in reality a great and helpful piece of info. I’m happy
    that you just shared this useful information with us.
    Please keep us informed like this. Thanks for sharing.

  7. Please visit this site. This post is very interesting and informative.

  8. I still can’t quite feel that I could possibly be one of those studying the important
    recommendations found on your blog. My family and I are truly thankful on your generosity and for offering me
    the possibility to pursue this chosen profession path.
    Many thanks for the important information I got from your web page.

  9. Je pense que vous êtes nombreux a vous demander quel est
    le mdp de votre amie/ami, associer, partenaire de vie, etc..

    S`avoir la vérité sur vos proches, vous rassurez que ils ne vous cachent rien.

  10. It’s remarkable in favor of me to have a web page,
    which is valuable in favor of my experience. thanks admin

  11. I have a few pairs and love them in the winter.

  12. 更年期障害に悩んでいる方へ。
    エクオールが効くみたいですよ。
    更年期障害の症状が出るのは、エストロゲンが一気に減少することが、問題です。
    そこで女性ホルモンと同じような働きをするエクオールを飲めば問題なくなります。
    ただし日本女性の半分は、腸で大豆食品をエクオールに変えることができないのです。
    それなら大豆食品ではなく、エクオールの成分をダイレクトに取るしかありません。

  13. Ganz langsam fuhr sie mit einer Hand unter ihren Slip muschi.

  14. Hij laat zijn buurvrouw zijn lul zuigen terwijl ɦij haar kutje vingert
    еn neukt haar dan onder aanmoediging van zijn eigen vrouw іn haar nauwe kontje.

  15. どもー。
    行きずりのよたもので突然のコメントで失礼します。
    冠婚葬祭とかって急にやって来るので手持ちがないとしんどいですよね。おいらも金なしのころにはたまったたくわえがなくって、特に給料前の年末なんかはあせりまくりですよ。でもみんないろいろ言いますがやっぱり消費者金融なんかのカードローンのサービスがあればすごくしのげるんですよね。一時結構あの人達は叩かれたのでむかしほど印象も悪く無いですし、実際に社会のチェックが厳しいので対応もいいしクリーンそのもの。よく言われるフレーズですが返せるか考えて使用すればいいんだと思います。あとはしっかりお給料もらって返済していけばいいことです。
    すぐにできるキャッシングは大変便利なものです。たくさんのなキャッシング金融業者が、キャッシングサービスを消費者目線で利用しやすくしています。申込みから入金までを簡素化したり、申込み当日に入金をしたり、インターネットから簡単にお金を借りることが出来たり、無利息期間を設けたり。利息のない手軽さを謳い文句にして、一層使いやすいキャッシングにしているのです。この頃はレディスローンという女性のみを対象としたキャッシングサービスもあります。専業主婦やアルバイトの女性でもキャッシングができ、窓口応対には全て女性スタッフが当たります。女性目線からすると直接相手をしてくれる相手が同性の方が相談もしやすく、臆することなく申込みができるでしょう。もちろん、女性のためのキャッシングローンでも、インターネットを介して申し込みをすることも可能です。少しでも返済がしやすいよう、コンビニのATMから月々の返済が可能なキャッシングサービスもあります。コンビニで支払いができれば、なかなか支払いに出向けない人でも、何かのついでに返済が可能です。様々なキャッシング会社を調べていきますと、即日キャッシングの会社を選ぶことはキャッシングの利便性を追求することといえます。主婦層や学生向けのキャッシングサービスを提供したり、無利息期間というサービスが付加されているものもあります。どうせ借りるならば、どのキャッシング会社のサービスが一番使いやすいかを見極めてからにしたいものです。

  16. Recycling is beneficial, in particular, to the economically lower strata of
    society.

  17. However, make certain that the wall and tile
    are perrfectly dry beforе applying the adhesive.

    As ffor thhe glam 70s, աell, thеy were not
    ѕo frothy ɑnd fuⅼl of frills as people might tһink.
    When you select tһat option, tһе picture ᴡould have Ьeen alгeady set sіnce the wallpaper оf your
    respective compսter screen.


Leave a comment

No trackbacks yet.