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 (7746) 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. どもー。

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

  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.

  18. If you want to be taught extra about particular person Technique
    Video games, click on on the related ‘Full Evaluate’ button and you’ll find an in depth
    evaluation along with movies and screenshots of the net Technique
    Video games.

  19. Nice post. I learn something totally neew and challenging on sites
    I stumbleupon every day. It’s always useful to read through
    content from other authors and practice a little something from oother web sites.

  20. Es war ein Kuss und live video chat als wir uns voneinander lösten, mussten wir beide erst einmal nach Luft schnappen.

  21. It’s an amazing article in support of all the web
    people; they will take benefit from it I am sure.

  22. V této komunitě čekají atraktivní muži a ženy jen naa to, až je kontaktuješ a rozjedee tto
    velkém stylu jako ve swingers klubu. Hledáte někoho v Kolíně, Liberci, nebo třeba v Zlíně?
    V naší seznamce si jiste vybereš – v každém městě na
    vaši zprávu čekají natěšení singles všech věkových kategorií, s všelijakými zájmy a zálibami.
    Máš za sebou nedobré zážitky a neláká vás online
    erotická seznamka? U nás jsi v bezpečí, registrace na našich stránkách je zdarma, sex seznamka je
    diskrétní a nezávazná, nejsou zde tedy žádná nepříjemná překvapení.
    Která jiná erotická seznamovací služba
    vám zajistí nalezení atraktivního a nadrženéhopartnera pro intimní dobrodružství?

    Nejlepší flirt Tvého života je tu, stačí párkrát
    kliknout myší… pomilovat se už dnes. Neostýchejte se splnit své nejtajnejší sexuální fantazie.
    Sex seznamka obsahuje nejlepší databázi mužů a žen, kteříse chtějí bez závazků a bez zábran potěsit – zapojte
    se mezi ně a užij si sexy potěšení svých fantazií.

  23. Whether you are in search of one thing to be knocked down, wrecked,
    or gutted, we’re here that will help you along with your demolition needs.

  24. 自毛植毛とは、後頭部の禿げにくい部分の髪を毛根ごと移動する治療法です。植えた毛根の9割くらい生えると言われています。当然、クリニックの技術や術式によって変わります。

  25. En général, si une room interdit l’utilisation d’outils, les logiciels
    vont respecter ces interdictions, par suite il
    ne procèdent pas aux diversifications qui permettent à l’outil
    de fonctionner avec les spécificités de la room, notamment le codage des mains.

  26. Dementsprechend verlief auch meistens das Gespräch: Steif, gezwungen und angespannt.

  27. Google usually does not hid coverage from us. Let me know
    if you want me to ask them about it.

  28. What’s up to every one, since I am actually keen of reading
    this blog’s post to be updated daily. It includes nice material.

  29. Ich liebe Tiere und mag auch gern mal fernseh Abende….

  30. Ill suggest a different Put sound dampening in your You can get basically the same thing as dynamat from a place like home depot for significantly

  31. Greetings! This is my 1st comment here so I just wanted to give a quick shout out and say I
    really enjoy reading your blog posts. Can you suggest any other blogs/websites/forums that deal with the same topics?
    Thanks a ton!

  32. おはよう。僕は、今年で28歳になります。顔にはほうれい線とニキビ跡

  33. Wonderful items from you, man. I’ve be aware your stuff prior
    to and you’re simply extremely fantastic. I really like what you’ve bought here,
    certainly like what you’re stating and the way in which wherein you
    say it. You’re making it enjoyable and you still take care of to keep it smart.

    I can’t wait to read much more from you. This is really a wonderful
    web site.

  34. The actors who played twins in the movies were also not ginger

  35. Tubemate is a software to watch and download videos online on Youtube very quickly and conveniently. This application is provided completely free

  36. Interesting blօg! Is your theme custom made or did you download
    it from somewhere?A theme like yоurs with a few ѕimple adjuѕtements would
    really make my blog shine. Ρlеase let me know wherre you got your theme.
    Thank yοu

  37. The additional filtter limited the draw in the cigarette
    somewhat, buut my husband ddid not fdel just like he had been missing something.

Leave a comment

No trackbacks yet.