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 (6841) Trackbacks (0)
  1. 急な借入が必要な時には、サービスの良い金融機関を活用することが大切です。実際に利用してみると、便利な資金調達を受けることができます。金融機関を選択する時は、慎重に申し込むことが大切です。

  2. For hottest news you have to pay a visit the web and on world-wide-web I
    found this web page as a finest site for latest updates.

  3. ZephylrinはL-トリプトファンなどを主成分とした男性用サプリです。L-シトルリンは西瓜などに入っている成分ですが、血管を拡張し、血液の流れを促す効果があることから、男性自身の増大を目指して飲んでいる男性もいます。L-トリプトファンは睡眠ホルモンの生成に欠かせないアミノ酸なので寝る前に飲むのが理想です。サプリを補助として、ミルキングなどの鍛錬を実施することが重要です。

  4. Free shipping on designer name brand sunglasses.
    Shop for designer name brand sunglasses from the best brands.
    Totally free shipping and returns.

  5. Simply desire to say your article is as astonishing.
    The clarity for your submit is just spectacular and that i can assume you are an expert on this subject.
    Well along with your permission let me to clutch your RSS
    feed to keep updated with approaching post.
    Thanks a million and please continue the enjoyable work.

  6. Aw, this was an extremely nice post. Taking
    a few minutes and actual effort to produce a
    superb article… but what can I say… I procrastinate a lot and don’t manage to get nearly anything done.

  7. Currently it appears like Drupal is the top blogging platform out there right now.

    (from what I’ve read) Is that what you are using on your blog?

  8. Fine way of explaining, and pleasant article to obtain data about my
    presentation subject matter, which i am going to deliver
    in institution of higher education.

  9. Oh my goodness! Incredible article dude! Thanks, However I am going through
    difficulties with your RSS. I don’t understand why I am unable to subscribe
    to it. Is there anyone else having identical RSS issues?
    Anybody who knows the answer will you kindly respond?

  10. I’ve been exploring for a bit for any high-quality articles or blog posts on this sort of area .
    Exploring in Yahoo I at last stumbled upon this website.

    Reading this info So i am happy to express that I have an incredibly excellent uncanny feeling I found out just what I needed.
    I most definitely will make sure to don?t
    fail to remember this website and give it a glance regularly.

  11. It’s going to be end of mine day, however before end I am reading this
    wonderful post to improve my experience.

  12. If some one wants to be updated with most up-to-date technologies then he must be visit this web page and be up to date everyday.

  13. naturally like your web-site but you need to check the spelling
    on several of your posts. A number of them are rife with spelling problems and I find it very bothersome to inform
    the reality however I’ll definitely come back again.

  14. When some one searches for his essential thing, thus he/she wants to be available
    that in detail, therefore that thing is maintained over

  15. I pay a visit each day a few web sites and
    sites to read articles, but this blog provides quality based articles.

  16. When I initially left a comment I appear to have clicked
    on the -Notify me when new comments are added- checkbox and now every time a comment is
    added I get four emails with the exact same comment.

    There has to be an easy method you are able to
    remove me from that service? Thank you!

  17. Your style is unique compared to other people I’ve read stuff
    from. Thank you for posting when you have the opportunity,
    Guess I will just bookmark this page.

  18. We absolutely love your blog and find many of your post’s to be exactly I’m looking for.

    can you offer guest writers to write content
    for you personally? I wouldn’t mind publishing a post or elaborating on a number of the subjects you write about
    here. Again, awesome web log!

  19. Hello mates, its wonderful article regarding cultureand completely explained, keep it up all the time.

  20. Humana People to People began implementing their jobs
    in China during 2007. One of the initial projects
    which was assumed was the Malaria work which targeted to distribute important information and protection on the problems to region residents.
    A Group Skill Progression and Child Aid project was then started
    in Zhenkang. A wonderful 13 plans were began in 2010 for
    a few of the biggest poor regions of the county. In addition to the Yunnan Province, developments were going in the Sichuan Province, Chongqing Area and Guangdong Area.

    Now, several plans that Humana has assumed within China includes treatment in countryside regions, earlier childhood learning that is
    built to offer Chinese kids a lead on the road to
    success, generating safer roads for Humana preschool children, giving fast HIV checking, establishing grower
    support groups and raising cash through charity occasions such as Humor
    Club China Nonprofit Show. Currently, there are 11 developments increasingly being completed all
    through 3 provinces in China as well as in more than 128 communities.
    Along with 280 collective beneficiaries, People to People creates hope and a greater future to
    these exhausted countryside regions.

  21. Good post. I learn something new and challenging on websites I stumbleupon everyday.

    It’s always interesting to read through articles from other writers and use something from their sites.

  22. Thanks for sharing your thoughts about Visit here. Regards

  23. Appreciation to my father who stated to me on the topic of this website, this webpage is
    actually awesome.

  24. What’s up, this weekend is good in favor of me, for the reason that this occasion i am reading this enormous informative paragraph here at my house.

  25. Thankfulness to my father who informed me on the topic of this web site, this webpage is truly remarkable.

  26. After checking out a handful of the articles on your blog, I
    honestly appreciate your way of writing a blog.

    I added it to my bookmark webpage list and will be checking back soon. Take a look at my website too and let me know what you

  27. What i don’t understood is in reality how you’re
    not actually much more well-liked than you might be right now.
    You are so intelligent. You know thus significantly with regards to this matter,
    made me for my part imagine it from so many numerous angles.
    Its like women and men aren’t involved unless it’s something to
    do with Girl gaga! Your personal stuffs outstanding.
    All the time take care of it up!

  28. There is also what frequently goes by the name of ‘open secret’ – that is truth acknowledged by numerous but in no way publicly
    confessed, by no means disseminated via the media, truth kept in a state of limbo, either simply because the
    time is not proper to disquiet the masses or because public acknowledgement would entail some penal consequences that
    the Establishment does not like to incur.

  29. Good answers in return of this matter with real arguments and telling the whole
    thing regarding that.

Leave a comment

No trackbacks yet.