Wednesday, May 11, 2011

PowerShell script to backup site collections, write a log file and send a email for failures

Are you still using VB script to backup your site collection, come on dude…? It’s time to use the power of power shell...

There are lots of scripts published for backing up site collection, what special in mine??

Let me tell you what...

1) This script actually skip’s the failed site collection and report an email as well write in the log file.
2) The Log file will be written on either ways, whether the site got succeeded or failed.
3) One more final thing, I am using -Nositelock in my script. lol


#+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
# This script backups a list of site collection from a “text“ document and # writes to log file with URL in
# either case if it is succeeded or failed, it also sends a email on every # single backup failure with the
# Respective URL and exception
# Created by KannaGanesh May 10 2011
#++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++

add-pssnapin microsoft.sharepoint.powershell
$date = (get-date).ToString()

# The below line reads the URL.txt file

$readfile = Import-Csv D:\URL.txt
$filepath

# The below four lines execute the backup and save in with URL Name (with Port # if available)

foreach ($line.URL in $readfile)
{$FilePath = “D:\backups\” + $line.Url.Replace("http://",””).Replace(“/”,”-“).Replace(":","-") + “.bak”;
backup-spsite -identity $line.URL -path $filepath -nositelock -force -errorVariable a -ea SilentlyContinue ;
$a

# The below if / else statement will write the log files and send a email for any failure

If ($a -ne $null)
{write-output "$date Backup failed for $line.URL with" $a | out-file D:\log.txt -append ;
$emailFrom = "from@example.com"
$emailTo = "emailed@example.com"
$subject = "Sitecollection Backup failed"
$body = "$line got failed, Please check the log files @ D:\log.txt for more details"

# Use commas for multiple addresses

$smtpServer = "Your SMTP Address"
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
$smtp.Send($emailFrom, $emailTo, $subject, $body)}
else
{write-output "$date succcess $line" | out-file D: \log.txt -append}
}


Ensure the following
1) Before executing this script, ensure you eliminate any unwanted spaces or # signs
2) Ensure your URL.txt file is in below format.
URL
http://URL1
http://URL2
http://URL3
3) Make sure your script has access to Url.txt and log.txt files,
4) Hope you have a valid SMTP service which can sent emails when there is a failure

Disclaimer

We have tested this script in our environment and confirmed to be working fine, please execute the same in dev / test environment before moving in to production to avoid any damage

Wish you all the success.

No comments:

Post a Comment