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 (8522) Trackbacks (0)
  1. horoscope verseau du mois d’aout horoscope du mois de juin vierge horoscope du jour pour le cancer journal
    des femmes horoscope horoscope noir gemeaux horoscope nrj heure compatibilite horoscope femme poisson homme taureau horoscope signe astrologique
    date horoscope mensuel juillet vierge 19 decembre
    signe horoscope l’horoscope humoristique horoscope de decembre 2017 horoscope homme vierge horoscope lion juillet aout
    2017 horoscope du jour poisson 3 decan horoscope pour elle lion horoscope du mois
    de fevrier cancer horoscope gemeaux 2018 amour horoscope poisson mois de juin horoscope mensuel
    cancer horoscope signe vierge horoscope de
    vendredi 30 juin 2017 liste des dates horoscope horoscope cancer sante mon horoscope du jour signe balance horoscope lion femme actuelle wc cancer horoscope horoscope 26 juillet 2017 vierge horoscope prenom et date de naissance horoscope du jour gemeau femme horoscope verseau 1er decan aujourd’hui horoscope personnalite des signes janvier horoscope signe
    le parisien horoscope gemeaux horoscope affinite humeur amour mon anniversaire aujourd’hui horoscope
    horoscope jour cancer homme horoscope cancer septembre horoscope verseau homme amour horoscope homme balance
    juillet 2017 horoscope poisson du mois de septembre horoscope sud ouest journal le meilleur signe de l’horoscope horoscope du jour capricorne homme horoscope mois lion horoscope du jour cancer rtl2 horoscope femme sagittaire horoscope de l’homme vierge tarot mon horoscope du jour l’horoscope est il vrai
    horoscope mois d octobre

  2. como saber si soy una persona vidente videncia visa barata alguem conhece
    vidente serio em portugal vidente rosa de luna como puedo ser una persona vidente vidente
    famoso venezolano vidente buena 806 mhoni vidente facebook
    2016 vidente gratis telefono vidente ana la gallega vidente 806 significado vidente bidente vidente gratis whatsapp soy
    vidente de nacimiento vidente particular barcelona vidente gratis por correo vidente buena sin cartas tarotista y vidente gratis mejor vidente murcia vidente famosos argentina vidente sin preguntas gratis
    vidente gratis por sms que significa ser vidente natural videncia buena y economica
    como lograr ser vidente tarot del amor mhoni vidente
    ana vidente gijon videncia del amor vidente gratis
    por whatsapp en argentina vidente lucia barlamar vidente
    buena que acierte tarot vidente economico el mejor psiquico del peru
    videncia por email gratis medium vidente sin preguntas alguna vidente buena en madrid vidente tarotista vigo busco vidente buena vidente
    natural visa anabel vidente en cantabria vidente telefono movil
    vidente valencia mislata vidente atiendo personalmente economico videncia por correo electronico gratis vidente sin cartas vidente en directo tarot
    vidente barato la vidente del amor discovery vidente seria y economica
    aida vidente sensitiva alguna vidente buena por telefono

  3. horoscope naissance 19 avril horoscope lion symbol horoscope du mois cancer homme horoscope du mois
    gemeaux 2017 horoscope de l’ete horoscope vrai
    ou pas horoscope journee cancer horoscope yahoo pour elle horoscope quotidien capricorne homme
    capricorne horoscope caractere l’horoscope gemeaux femme horoscope du jour amour poisson horoscope
    detaille taureau christine haas horoscope 2017 balance horoscope signe de
    feu gralon horoscope vierge horoscope du jours vierge mon horoscope poisson amour horoscope 20 avril horoscope capricorne juillet horoscope
    amerindien castor horoscope mensuel capricorne horoscope lion homme amour
    du jour l’horoscope du mois d’avril horoscopes du jour vierge horoscope
    quotidien horoscope du jour cancer deuxieme decan horoscope du jour 12 janvier horoscope de poisson 2eme decan horoscope vierge
    juin 2017 horoscope capricorne homme du jour horoscope du journal le monde horoscope professionnel du jour
    horoscope revue mensuel horoscope du jour cancer
    femme amour horoscope verseau rtl horoscope sante des femmes elle astro horoscope du jour horoscope janvier 2019 horoscope homme lion 2018 horoscope taureaux homme radio contact horoscope horoscope du
    jour pour le signe de la balance horoscope juin 2017 lion compatibilite amoureuse horoscope cainer horoscope cancer horoscope poisson premier decan astrowow horoscopes horoscopes du mois de novembre
    horoscope balance du jour meteocity poisson horoscope

  4. can psychics predict their own future the daily mash psychic bob rita rogers psychic psychic information meaning psychic fair newcastle nsw psychic chicago illinois best psychic reader on etsy psychic readings perth scotland psychic shay reviews psychic tv themes youtube angel
    psychic reading pittsburgh online psychic jobs free psychics readings
    by phone psychic handshake game psychic senses spirituality famous male psychic medium ask peter psychic questions psychic astrologer deborah young free sms psychic reading psychic mediums
    in long island ny superior psychic center north fort
    myers fl psychic readers in orlando florida the best online psychics local psychic
    mediums madison wi best psychics in kansas city mo spiritual enlightenment meaning in hindi vincent genna psychic psychic
    energy definition psychic abilities are not real reviews on hollywood psychics universal psychic guild monthly horoscope linda drake psychic ask real psychic free
    question amanda’s psychic readings birmingham’s best
    street psychic peter serraino psychic scams new york times dr iris carlton psychic best psychics in atlanta
    psychics in calgary ab psychic web chat free what does the new testament say about psychics psi psychic solutions psychic warren nj a psychic
    told me i am cursed psychic mediums in kansas city mo bandcamp psychic tv are you a psychic quiz home visit psychic readings barb’s psychic serpent trilogy psychic in florida commune do psychic readings really
    work

  5. astrology signs january 24 starseed astrology signs pisces
    zodiac astrology horoscope january 31 1984 astrology yin and yang
    astrology legitimate astrology sites pisces horoscope astrology king nadi astrology is true or false astrology horoscope zodiac signs free astrology predictions for today astrological rulerships free relocation astrology report
    ascendant in vedic astrology taurus daily astrology chinese astrology signs and elements peridot gemstone astrology dr rao astrology symbols astrology scorpio capricorn astrology zone house in astrology calculator my astrology sign rising
    virgos astrology sign may 20 astrology sign vedic astrology singapore zodiac astrology signs
    dates free vedic astrology calculator mc astrology pisces chaldean astrology talisman most
    accurate astrology horoscopes believe in astrology pisces ascendant woman vedic astrology greek symbols for astrology astrology cancer men famous tamil astrologer in bangalore jupiter retrograde astrology meaning
    cafe astrology daily capricorn astrology degrees minutes cafe astrology rising sign scorpio free tarot astrology
    predictions aries astrologically crossword last word in astrology astrology first house stellium my
    astrology as per date of birth basics of astrology in marathi free natal
    astrology beauty astrology aspects april 23 astrology sign natal astrology cafe current astrological aspects astrology zodiac signs cancer online name
    astrology

  6. months and their astrological signs astrology cancer today 5th house ruler astrology astrology zone horoscope aries ceres astrology meaning what does 8th house
    mean in vedic astrology prem vivah yog in vedic astrology what is
    house in astrology astronomical society solar eclipse glasses how to understand aspects astrology astrologist
    job what is an ascendant in astrology pisces daily horoscope darkstar astrology free astrology
    by date of birth and time in kannada february 28 astrological sign what is a cusp
    in astrology deneb algedi astrology april 27 1985 astrology fortune telling by astrology
    june 5th astrology symbols of astrological signs the astrology room lovescopes astrological forecast cancer
    vedic astrology sun sign aquarius astrology sign for april 20th astrology
    36 cancer astrology week ahead astrology weekly sports
    astrology signs february 22 astrology for gemini
    daily astrological signs date of birth chinese astrology pig ketu astrologykrs astrological sign april 27 astrology
    uranus retrograde vedic astrology houses and body parts astrology months
    and dates love calculator astrology in tamil astrology help for job astrology july 14 sign venus 11th house vedic astrology free marriage age prediction vedic astrology
    origin of astrology in world free real astrologers what is
    my future job astrology conjunction astrology orb astrologer in bur
    dubai leo king astrology uncut signe astrologique verseau scorpio
    daily vedic astrology astrology born august 22

  7. signification signe astrologique gemeaux msn accueil
    astrologie serpent astrologie chinoise signe astrologique pour le moi
    de mai l ascendant astrologique site d astrologie serieux astrologie homme gemeaux femme scorpion signe astrologique bonne entente
    astrologie homme verseau femme sagittaire signe astrologique homme cancer femme balance signe astrologique d’une personne nee le 28 fevrier caracteristiques signe astrologique taureau
    sagittaire signe astrologique definition compatibilite amoureuse signe astrologique zodiaque signe
    astrologique belier homme en amour signe du zodiaque 21 mai interpretation junon astrologie
    signe astrologique date 26 avril signe astrologique feu et air quel est le signe zodiaque du mois de
    mai signe astrologique caractere homme elle astrologie sagittaire astrologie cancer novembre signe astrologique du lion homme signe astrologique grec
    poisson signe astrologique femme astrologie scorpion ascendant cancer
    signe astrologique signification taureau astrologie femme lion homme belier signe zodiaque pour le mois de mars signe astrologique pour le 15 mai signe zodiaque
    du 22 novembre 21 decembre signe astrologique taureaux astrologie
    astrologie femme poisson et homme taureau
    signe astrologique 20 mai 2017 signe zodiaque dans le ciel 3 fevrier
    signe astrologique chinois les pierres precieuses et les signes du zodiaque compatibilite signe astrologique gratuit compatibilite signe astrologique date de naissance signe zodiaque
    de decembre pendentif signe astrologique homme lion astrologie 2017 scorpion signe astrologique homme signe zodiaque de decembre nouveaux signes astrologiques astrologie science ou baratin signe astrologique du moi
    de janvier signe astrologique verseau amour les signes astrologiques les plus fort

  8. orlando florida psychics is psychic weak to ghost
    ana’s psychic readings albuquerque nm phil jordan psychic biography psychic recommendations
    uk psychic lisa lee nyc psychic derek calibre new york ny maria psychic kitchener famous psychic readers mrs lee psychic groupon how can psychics tell the future best psychic in sf san francisco ca free call psychic reading spiritual meaning of migraine headaches
    psychic readings for free online psychic
    cincinnati oh psychic experience alien psychic contact northampton psychic colonial belle
    psychic cruise psychic reading psychic catholic best psychic readings australia mental disorder symptoms checklist psychic readings durban do genuine psychics exist psychic readings in duluth mn psychics in youngstown ohio psychic ara san antonio tx psychic girl in coffee
    shop how to strengthen my psychic powers authentic psychic get accurate psychic
    readings psychics in essex psychic temple plays music for airports vinyl
    psychic readings downtown vancouver how to become a phone psychic pregnancy psychic
    reading melbourne yugioh psychic counter improving your psychic ability cat power psychic
    hearts lyrics top psychics in minneapolis mn seattle psychics reviews phone psychic reading dog psychic psychic susan houston area psychics insurance for mediums
    and psychics psychic in sandy springs ga psychic tarot cards meanings psychic library test

  9. horoscopes for your exact birthday reliable horoscope astrology week ahead horoscope capricorn horse
    horoscope 2019 online love horoscope reading horoscope cosmopolitan august 14 pinoy daily horoscope today horoscope for libra in urdu pisces work
    horoscope today may 22 horoscope cusp jan 22 horoscope horoscope pisces career
    today my love life horoscope by date of birth sagittarius horoscope for
    tomorrow career may horoscope today elle magazine sagittarius daily horoscope free love horoscope libra what horoscope is august 29 bengali horoscope 2018 leo july
    horoscope 2017 scopion horoscope what is may’s horoscope name horoscope for
    june 22 birthday june 30th horoscope 2017 most accurate aquarius
    love horoscope libra monthly horoscope kamal kapoor capricorn dec love horoscope tomorrow horoscope for cancer in hindi cancer love horoscope weekly elle horoscope weekly cancer 8 degrees
    scorpio horoscope spot onion horoscope april 2017 aries snake love horoscope aries
    love western horoscope for today scorpio career horoscope daily august 22 horoscope 2017 the bible and horoscope signs signs the onion horoscope april 2017 gemini horoscope birthstone aries financial
    horoscope 2017 your horoscope by date of birth scorpio horoscope physical
    traits horoscope for week of july 3 horoscopes by birth date june 26 birthday horoscope what is aquarius horoscope sign daily horoscopes for pisces horoscope aquarius today love labour horoscope horoscope hindi what is a horoscope rising sign

  10. tarot del gratis del amor tirada del tarot gratis sobre trabajo cartas del tarot tarot
    amor tirada rapida mi carta del tarot del amor consultas de tarot tarot voy a
    tener suerte en el amor tirada de tarot gratis del amor del si o no tirada de las 3 cartas del tarot gratis formas de tirar el tarot rider leer las cartas del
    tarot gratis en linea tarot gratis carta del dia los arcanos
    tarot economico visa el tarot del amor si o no gratis como interpretar las cartas del tarot
    en una tirada tiradas de cartas gratis de tarot tarot
    trabajo hoy tarot 3 minutos gratis cartas de tarot para vender
    tarot acuario hoy tirada de cartas tarot gratis en linea tarot gitano amor 2014 cartas de tarot
    de amor gratis tarot suerte para hoy gratis tirada
    de tarot gitano tirar cartas de tarot de amor gratis tarot del amor gratis si o no tarot gratis 2015 cursos tarot
    en madrid tarot del amor gratis 2012 visa tarot leer
    las cartas gratis del tarot tarot del dia de hoy tarot 3 euros
    10 minutos carta del amor tarot tarot luz horoscopo de hoy amor tarot
    cancer tarot de pedro engel 2015 arcano numero 8 del tarot tarotistas famosos en chile tarot consulta particular tarot piscis hoy arcanos leer tarot gratis amor significado del sol
    y la luna en el tarot pregunta al tarot del amor si o no juego
    del tarot automatico tarot tauro 2017 abril tarot amor autentico tarot libra abril 2017 tarot gratis por mensaje de texto tarot oraculo gratis 2017

  11. vidente gratis por wasap que significa vidente en la biblia
    vidente buena que acierte cristina vidente torrelavega paqui vidente en malaga vidente una pregunta gratis vidente del amor aida luz valencia vidente tarot
    vidente amor aida vidente colombiana vidente
    fiable barcelona irma lucia vidente de fatima el mejor vidente del mundo gratis vidente cristina marksman vidente por chat gratis videncia economica 0.41 Buena vidente en madrid para ir a su consulta vidente bueno
    y gratis vidente en velez malaga vidente predice futuro de venezuela como lograr ser
    vidente blanca san antonio vidente gratis vidente por correo vidente valencia voluntad vidente fiable gratis marcos vidente alzira facebook tarotista vidente
    gratis consulta de tarot y videncia gratis medium vidente sin preguntas mhoni vidente
    verdad o mentira encontrar una buena vidente vidente
    rosario explosion consulta vidente 24 horas foro videncia como hacer para ser vidente jose vidente television persona vidente gratis
    videncia amor gratis buen vidente bilbao vidente bola de cristal gratis vidente gratis telefono fijo significado vidente bidente tarotista vidente medium flor hernandez vidente natural y medium vidente sevilla gratis videncia particular vidente bueno en zaragoza
    vidente famosa de mexico como tener el poder de ser vidente vidente una pregunta gratis busco una buena vidente en barcelona

  12. voyance gratuite avec voyant virtuel plug rtl voyance meilleure voyance yanis voyance horoscope 2016 cancer voyance privee
    telephone voyance gratuite par chat en direct sans inscription arnaque voyance beatrice voyance lorient voyance nom prenom date de naissance fabienne quaranta voyance voyance gratuite sans cb par telephone voyance direct
    gratuite chat voyance sans cb boule magique
    voyance voyance gratuite sans carte bancaire sans attente boule voyance gratuite oracle
    ge voyance gratuite maud kristen voyance voyance
    amour gratuite reponse immediate voyance gratuite immediate par tchat amour voyance gratuite par chat en direct pendule voyance voyance pendule avis salon de la voyance 2015 nord voyance
    avenir gratuite voyance date de naissance amour voyance amoureuse
    gratuit voyance arabe sans attente voyance gratuite par sms 06
    voyance cartomancie angers voyance gratuite oui ou non carte voyance tarot gratuit voyance gratuite carte en ligne eva m voyance voyance date de naissance et prenom helena voyance gratuite tirage de carte de voyance voyance sante gratuite ligne voyance en direct gratuite sans attente voyance
    gratuite par mail isabella voyance en amour voyance amour gratuite en direct jeu de tarot voyance en ligne gratuit livre initiation voyance
    ma boule de voyance jeux de carte voyance gratuite tchat
    voyance direct gratuit voyance moins 30 euros voyance strasbourg
    voyance audiotel immediate voyance gratuit

  13. carte tarot gitane tarot gratuit fiable amour tarot facile oui non combinaison carte tarot soleil comprendre tarot divinatoire tarot
    amour voir pour savoir voyance par tarot gratuit tarot club
    wintzenheim tirage tarot serieux gratuit viviane voyance tarot gratuit tarot divnatoire tarot a cinq
    gratuit tarot positif gratuit tarot en ligne voyance tarot divinatoire gratuit sante tirage tarot gratuit
    lenormand tirage tarot celtique tarot wiki voyance tarots mon tarot amour gratuit tarot gratuit oui non en ligne tarot voyance 2017 liste
    carte tarot divinatoire regle crapette avec jeux tarot voyance carte tarot
    tarot rtl sms tarot oracle amour gratuit combinaison carte tarot soleil tarot gratuit
    amour tirage tarot du prenom gratuit tarot persan tirage tarot oui non fiable tirage tarot 1 carte
    tarot divinatoire cartomancie gratuit tirage
    tarot gratuit oracle g bz tarot gratuit combinaison tarot amoureux lame tarot 18 tirage
    tarot gratuit amour oui non tarot gratuit du travail avenir par le tarot gratuit boutique tarot divinatoire paris tirage tarot divinatoire immediat tarot regle a 5 tarot du jour amour
    oui non tirage tarot gratuit fiable tarot divinatoire gratuit reponse oui
    non tarot en ligne a 5 sans inscription voyance par tarot gratuit en ligne carte tarot marseille 5 tirage tarot
    avenir gratuit

  14. This year’s preseason games in tthe National Football League given much excitement to each andd every
    sports enthusiast. Since you are a client, you have every one of the options to seek out the finest wwebsite that has a good offer.
    A local secondary school, the Peninsula High School, submitted the name Seahawks.


Leave a comment

No trackbacks yet.