The script gets input from BackupRestoreDetails.csv file which has the details on SourceURL, DestinationURL, DatabaseServer, DatabaseName . The script and input CSV file format is attached.
$LogTime = Get-Date -Format yyyy-MM-dd_hh-mm
$LogFile = ".\BackupRestorePatch-$LogTime.rtf"
# Add SharePoint PowerShell Snapin
if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null ) {
Add-PSSnapin Microsoft.SharePoint.Powershell
}
$scriptBase = split-path $SCRIPT:MyInvocation.MyCommand.Path -parent
Set-Location $scriptBase
#Deleting any .rtf files in the scriptbase location
$FindRTFFile = Get-ChildItem $scriptBase\*.* -include *.rtf
if($FindRTFFile)
{
foreach($file in $FindRTFFile)
{
remove-item $file
}
}
start-transcript $logfile
Function BackUpRestore([String]$SourceURL, [String]$DestinationURL, [String]$DatabaseServer, [String]$DatabaseName)
{
$Site = get-spsite $SourceURL
$SiteID = $Site.ID.GUID
Write-host "Creating folder for the backup" -fore Magenta
New-Item $scriptbase\$SiteID -type directory
Write-host "folder created for the export" -fore Magenta
$BackupPath = $scriptbase + "\" + $SiteID + "\" + $SiteID + ".bak"
write-host "Backup path is " $BackupPath -fore cyan
Write-host "Performing backup for the site " $SourceURL -fore yellow
Backup-spsite -identity $SourceURL -path $BackupPath
write-host "Backup completed" -fore green
Write-host "Performing restore on site " $DestinationURL -fore yellow
Restore-Spsite -identity $DestinationURL -path $BackupPath -DatabaseServer $DatabaseServer -DatabaseName $DatabaseName -confirm:$false
Write-host "Restore completed for the site " $DestinationURL -fore green
Write-host "Deleting folder" $scriptbase\$SiteID
remove-item $scriptbase\$SiteID -recurse -confirm:$false
write-host "Folder deleted successfully"
}
function sendMail{
Write-Host "Sending Email"
#SMTP server name
$smtpServer = "SMTP address"
#Creating a Mail object
$msg = new-object Net.Mail.MailMessage
#Creating SMTP server object
$smtp = new-object Net.Mail.SmtpClient($smtpServer)
#Email structure
$msg.From = "[email protected]"
$msg.ReplyTo = "[email protected]"
#For multiple to address, seperate the address with comma
$msg.To.Add("[email protected],[email protected]")
$msg.subject = "Backup/Restore Completed"
$msg.body = "Backup/Restore Completed."
#Sending email
$smtp.Send($msg)
}
write-host "You have choosen to do an BACKUP/RESTORE" -fore cyan
write-host "Please place the BackupRestoreDetails.csv under the folder where the powershell script is placed" -fore yellow
sleep(3)
$ans = read-host "Did you place the file? (y/n) "
if($ans -eq 'y')
{
$csvfile1 = $scriptbase + "\" + "BackupRestoreDetails.csv"
import-csv $csvfile1 | where {
BackUpRestore $_.SourceURL $_.DestinationURL $_.DatabaseServer $_.DatabaseName
}
sendMail
}
else
{
write-host "The user hasn't placed the file and choosen to exit" -fore cyan
}
stop-transcript