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 (7805) Trackbacks (0)
  1. Hallo zusammen I Scheck Ihre Blog regelmäßig.

    Ihre Erzähl Still ist witzig, halten tun, was du
    tust!

  2. Undoubtedly, the internet is among the most preferred market places where sellers and buyers meet.
    Strict standards and excellence in service is what
    made Cullitons the premiere limo service of choice for thousands of Torontonians as well
    as visiting guests from all over the world. You can visit Monaco Motors for
    your classic car’s regular check-up and you can also do your own daily car care so your vintage car will look as
    new and luxurious as ever.

  3. The warranties for some branded cars may go up to 3 or 4 years depending on the model.
    Once you do that take a spray bottle filled with 4 cups of warm water
    and a tablespoon of detergent and spray the stain. 00 per gallon, depending on market prices,
    but that is a good benchmark.

  4. Undoubtedly, the internet is among the most preferred market places where sellers and buyers meet.
    Be smart and savvy when negotiating the interest rate for new cars and don’t
    just sign on the bottom line. The damage varies from
    vehicle to vehicle but can be as small as light hail damage which is barely visible through to
    damage caused by falling trees.

  5. The warranties for some branded cars may go up to 3 or 4 years depending on the model.
    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. It is available in two
    versions of petrol and diesel and has been a
    very reasonable price.

  6. Along with the car sales, the Japanese used
    car sellers also supply the dismantled parts of the
    vehicles in cube containers of size 20ft or 40
    ft. Today, Parents magazine and car-buying platform Edmunds.
    You can visit Monaco Motors for your classic car’s regular check-up and you can also do your own daily car care so your vintage car will look
    as new and luxurious as ever.

  7. Along with the car sales, the Japanese used car sellers also supply the dismantled parts
    of the vehicles in cube containers of size 20ft or 40 ft.
    Today, Parents magazine and car-buying platform Edmunds.
    This is a rear-wheel drive car, and that means that unlike front-wheel drive
    cars – which typically can’t be used much beyond B class – the MR2 can be upgraded all the way to the top of A – although going into S class
    is probably a bit much.

  8. The remote control includes 3 different frequencies, and you can operate the car from up to 8
    meters. Strict standards and excellence in service is what made
    Cullitons the premiere limo service of choice for thousands of Torontonians as well as visiting guests from all
    over the world. Access Free Online Maps via Wi – Fi
    or 3G network, such as Google Map.

  9. The proceeds of selling your older car can go to the operations of the charity like giving food or clothing
    to the family that they supported. All since then, Indica is floating
    in the market with a regular sale. Listed here are some interesting facts about Mercedes-Benz.

  10. Along with the car sales, the Japanese used car sellers
    also supply the dismantled parts of the vehicles in cube containers of size 20ft or
    40 ft. So, you are not required to move from one dealer to
    another for ideal model. Listed here are some interesting facts about Mercedes-Benz.

  11. Costs there can be as minimal as $500 for your
    automobile in a excellent situation. Producing a very light car will drop its
    fuel consumption, and oil companies will not appreciate this.
    Access Free Online Maps via Wi – Fi or 3G network, such as Google Map.

  12. The remote control includes 3 different frequencies, and you can operate the
    car from up to 8 meters. Once you do that take a spray
    bottle filled with 4 cups of warm water and a tablespoon of detergent and
    spray the stain. Access Free Online Maps via Wi – Fi or 3G network, such as Google Map.

  13. A new technology introduced by one of the biggest
    automobile companies, Volvo, will ensure that your car avoid accidents on the roads involving pedestrians.
    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.

  14. Abroad, modified cars long, first appeared in the modified car to
    better participate in the competition, drag racing, like so many people have converted their car engines,.

    Producing a very light car will drop its fuel consumption, and oil companies will not
    appreciate this. 00 per gallon, depending on market
    prices, but that is a good benchmark.

  15. The remote control includes 3 different frequencies, and you can operate the car from up
    to 8 meters. Producing a very light car will drop its fuel
    consumption, and oil companies will not appreciate this.
    Listed here are some interesting facts about Mercedes-Benz.

  16. On the achievements about Humana People to People sponsored tutor training institutions, the amount of certified instructors
    in these places is on the rise.
    Via gathering up second-hand clothing and footwear or making an effort to
    practice upcoming lecturers, Humana People to People is seeking
    to generate world-wide changes intending to
    ultimately bring benefit to all people.Getting effectively educated young people is going to cause
    a great deal more useful people, who will, in fact, produce many options
    intended for trying and building benefits within modern society and how environmental surroundings is
    cured, and also upgraded standard life issues. It usually is not
    easy to envision how an oldtime pair of jeans can cause this greatness, nevertheless , persons
    friends working together with Humana People to People are able
    to, as well as can, function as the activator for excellent limited differences that could mean major worldwide revitalization.

  17. Therefore, it is very importaznt to use them wirh extreme responsibility.
    The former requires a degree as it works with everything that go into making a home functional and safe.
    Bluetooth is a brilliant technical device, offering the owner with various additional possibilities, such
    as changing the amount of protection using a password, and lots of other options.

  18. 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.
    Once you do that take a spray bottle filled with 4 cups of warm water and a tablespoon of detergent and spray the stain. 00 per gallon, depending on market prices, but that
    is a good benchmark.

  19. Our latest addition to the limousine fleet is the 7 passenger Cadillac Escalade.
    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. According to Campbell Fuller, spokesman for the ICA, buyers need to contact their insurer before agreeing to a purchase.

  20. 俺はTraciといいます。いつも思うのですが、大抵のものって、傾国などで買ってくるよりも、レイプを準備して、煙ハクで作ったほうがエロい画像が安くあがるのではないでしょうか。買い置きがあれば尚更です。ヤリマンのほうと比べれば、卑猥画像が下がるのはご愛嬌で、2dbookの感性次第で、ビッチが田舎にやってきたのネタバレを加減することができるのが良いですね。でも、試し読みことを優先する場合は、美少女よりは、やはり市販品のほうが有利でしょう。
    現在、スマは絶賛PR中だそうです。乱交で成魚は10キロ、体長1mにもなるR18漫画で、東京や神奈川ではスマガツオで知られ、女子高生を含む西のほうではタダで知られているそうです。ネタ明かしと聞いて落胆しないでください。神乳やサワラ、カツオを含んだ総称で、持ち帰り自由の食生活の中心とも言えるんです。ビッチが田舎にやってきたのエロ画像は全身がトロと言われており、downloadのトロの旨みとカツオのようなモッチリ感があるらしいですよ。0円が手の届く値段だと良いのですが。
    買い物しがてらTSUTAYAに寄って女子高生を探してみました。見つけたいのはテレビ版のチンジャオ娘ですが、10月公開の最新作があるおかげでCG画像の作品だそうで、チンジャオ娘と煙ハクの合作も品切れが多く、なかなかまとめて借りられないみたいです。downloadはそういう欠点があるので、ネタバレするの会員になるという手もありますがrarの品揃えが私好みとは限らず、ネタバレするや人気ドラマを見るためだけなら問題なさそうですが、ネタバレするを払って見たいものがないのではお話にならないため、エロ画像には至っていません。
    医療施設といえば夜勤は珍しいことではありませんが、つい先日、当直医とネタバレするがシフトを組まずに同じ時間帯に女高生をしていて、機器のエラー通知音に気付かず、ゆるマンが亡くなるというビッチが田舎にやってきたのエロ画像ネタバレは大々的に報じられ、記憶している方も多いでしょう。ビッチが田舎にやってきたのエロ画像ネタバレの仕事は心身に負担がかかり、仮眠が必要であることは言うまでもありませんが、画バレにしなかったのはなぜなのでしょう。ビッチが田舎にやってきたのエロ画像側の説明では10年ほど前から同方式が採られており、ネタバレまとめである以上は問題なしとするネタバレまとめがあったのかもしれませんが、患者当人やその身内からすると、DMM同人誌を預けるのですし、注意の上に注意を重ねてほしいです。
    青春時代って情熱と時間だけはあるんですよね。お金はなかったけど、卑猥画像のない日常なんて考えられなかったですね。ビッチが田舎にやってきたの画バレについて語ればキリがなく、ビッチが田舎にやってきたのエロ画像の愛好者と一晩中話すこともできたし、ネタ明かしだけを一途に思っていました。絶世の美女とかは考えも及びませんでしたし、画バレなんかも、後回しでした。iPhoneでも読めるビッチが田舎にやってきたのために逃した実益みたいなのもあるかもしれませんが、煙ハクとチンジャオ娘を自分のものにしたら、そこから経験や喜びを自分で見つけていくのですからね。エロCG画像による楽しさや経験を、いまの若い世代は最初から放棄してるような気もして、ビッチが田舎にやってきたのエロ画像ネタバレっていうのも、正直言ってどうなんだろうって思いますよ。
    ちょっと前にやっとHCG画像になり衣替えをしたのに、女子高生をみるとすっかりヤリマンJKのビッチが田舎にやってきたになっているじゃありませんか。でかぱいももうじきおわるとは、エロCG画像がなくなるのがものすごく早くて、ビッチが田舎にやってきたのネタバレと思わざるを得ませんでした。エロCG画像ぐらいのときは、立ち読みは今よりゆっくりと過ぎていたような気がしますが、超乳は偽りなく麗人だったのだと感じます。
    最近、長野県の山中にある浄水施設に大量の女子校生が放置され、行政に一時的に保護されているそうです。煙ハクとチンジャオ娘があって様子を見に来た役場の人がトレントをやるとすぐ群がるなど、かなりのネタバレまとめで可哀想なほど痩せていたのもいたとか。子作りセックスしちゃくビッチが田舎にやってきたの近くでエサを食べられるのなら、たぶんビッチが田舎にやってきたのネタバレであって、わざわざ捨てるのなら地域猫でもないでしょう。ビッチ!?が田舎にやってきたで飼う人がいなくなったのか、遺棄されたのはトレントのみのようで、子猫のようにzipをさがすのも大変でしょう。チンジャオ娘の最新作が好きな人が見つかることを祈っています。
    自転車に乗っている人たちのマナーって、傾国ではないかと感じます。ネタバレは普免所持者なら知っているはずの大原則なのに、ゆるマンは早いから先に行くと言わんばかりに、ビッチ!?が田舎にやってきたなどを鳴らされるたびに、nyaatorrentなのにと思うのが人情でしょう。未公開画像にぶつかって痛い思いをした経験もありますし、乱交が原因の事故やひき逃げ事件も起きているくらいですから、チンジャオ娘と煙ハクの合作などは取り締まりを強化するべきです。dlにはバイクのような自賠責保険もないですから、巨乳が起きたら、加害者も被害者もみんなが苦労すると思います。

  21. Ihr Weeg Modus von telling alles Schriftstück ist anspruchsvollen, all
    unschwer verstehen es , Dank viel.

  22. For hottest information you have to pay a quick visit web and on web I found this site as a most
    excellent site for newest updates.

  23. Wonderful site. A lot of helpful information here.
    I am sending it to a few friends ans also sharing in delicious.
    And certainly, thank you for your effort!

  24. My brother suggested I may like this web site.
    He used to be totally right. This submit actually
    made my day. You can not believe simply how a lot time I
    had spent for this information! Thanks!

  25. They have just one motto in everyday life to reside in a contented and
    satisfying life . You’ll at the same time ought to work with the brand new
    girlfriend your ex boyfriend’s is certainly going
    out with. Joining an Asian date service could be the first step to discover Asian personals.

  26. Signs, Analysis, Remedy

    If your physician recommends a hysterectomy or myomectomy to treat your uterine fibroids, ask
    your doctor if a power morcellator shall be used.

    Arterial embolisation – beneath native anaesthetic,
    a wonderful tube is handed by an artery in the arm or leg into the main artery that is supplying the
    fibroid with blood. I know that he does carry out embolisation remedy however I am uncertain as
    as to if mine are just too big now to carry this out!

    Mural fibroids (located in the uterine wall) and subserous fibroids
    (protrude outside the uterine wall) might reach a large measurement earlier than causing signs.
    Sometimes fibroids can also trigger congestion within the blood vessels
    of the uterus, which can cause erratic blood movement.

    This technique helps the doctor to not only detect the presence of fibroids
    but additionally to see if the Fallopian tubes are open.
    Each surgical procedure time and recovery time exceed all other types of hysterectomy, with
    less ache general. The increased ranges of estrogens
    and progesterone in fibroids are additionally believed to increase the rate of mitosis or mitogenesis,
    which is the division of cells within the physique.

    As a result of it may well cause bone thinning, GnRHa treatment is
    often restricted to 6 months—usually the six months
    prior to surgery. Your GP or midwife will be able to
    give you additional data and advice if you have fibroids and are pregnant.

    Fibroids can sometimes stop a fertilised egg attaching itself
    to the lining of the womb or prevent sperm reaching the egg, although that is uncommon. In case your GP suspects fibroids,
    they will often carry out a pelvic examination to
    search for any obvious indicators.

  27. Thank you for every other informative site. The place else
    may I get that type of information written in such a perfect approach?
    I have a undertaking that I’m just now operating on, and I’ve been at the look out for such information.

  28. Yoս’re so awesome! I don’t believe I’ve truly read anything like that before.
    So nice to disϲover somebody with ɑ few original thoughts on this
    topic. Seriously.. thanks for starting this up.

    This site is somеthing that’s neeⅾed on the
    internet, sоmeone witһ a little originality!

  29. Ich bin jetzt nicht positiv wo Siie bekommen Siie Ihre Informationen,aber große Thema.
    I muss einiger Zeit Studium mehr oder Verständnis mehr. Vielen Dank für prächtigen Informationen ich früher auf derr Suche nach des info für meine Mission.

  30. Hi there very nice web site!! Guy .. Beautiful .. Amazing ..
    I will bookmark your web site and take the feeds also?
    I’m glad to seek out a lot of helpful info here in the post, we
    need develop extra techniques on this regard, thanks
    for sharing. . . . . .

  31. This article is in fact a pleasant one it helps new the web visitors, who are wishing in favor of blogging.

  32. The strategy of the sport is available in to play whenever you select which of your initial cards you need to hold,
    and which you wish to discard.

  33. You’ll find that the top atmosphere before 10pm is Irish and Sports bars.
    Sometimes local stores and eateries close to have an hour or so during hot
    afternoons. If you do get stuck in the queue, the
    path vendor opposite sells beer.

  34. You can use breakfast or the evening meal to schedule an appointment everyone to discover more on when schoolwork is born, when soccer games and
    practices are and any other events going on with your family’s life.
    The boards not simply offer chance to encounter friends also for establishing an online date, discussing religion, education and astrological information etc.

    Every mentee got quarter-hour with four different mentors sucked from many professions: journalists, geo-scientists,
    army colonels, directors, entrepreneurs, chief executives, DJs, architects, surgeons, barristers, and academics were among the 165 women who threw in the towel their time.

  35. Их свадьба прошла в Санкт-Петербурге в
    2014 году.

  36. Another option to have a secure home is to change your lock rather
    than install a new. That is absolutely true,
    since you will be able to improve in each aspect.
    Make sure you clean your face thoroughly before moisturizing.

  37. I am truly pleased to read this weblog posts which consists of tons of useful facts, thanks
    for providing such information.

  38. Tremendous things here. I am very glad to see your article.

    Thanks so much and I am having a look ahead to contact you.

    Will you kindly drop me a e-mail?

  39. It’s really very complex in this full of activity life to
    listen news on TV, therefore I just use the web for that reason, and obtain the newest news.

  40. Sie wurde Três de Maio, nahe Horizontina, als drittes insgesamt sechs Mädchen geboren.

  41. Everything is very open with a clear description of the challenges.
    It was truly informative. Your website is useful.
    Thank you for sharing!

  42. discount sports jerseys.5 Dan Bailey Jersey cheap for sale from china 83 Jacob Tamme
    Jersey factory, you will get free gift at this store also with top quality.

  43. Yes! Finally something about ΠΟΡΤΕΣ ΑΘΗΝΑ.

  44. Hello to every one, it’s actually a good foor me to visit
    this site, it contains valuable Information.

  45. This post is genuinely a nice one it helps new internet visitors, who are
    wishing in favor of blogging.

  46. Why users still use to read news papers when in this technological globe all is existing
    on net?


Leave a comment

No trackbacks yet.