Monday 6 August 2012

Site Collection Restore Script

If we want to restore a single site collection through Powershell we use the following command:

Restore-SPSite "SiteURL" -path "Pathofbackupfile\backupfilename.bak" -Force -DatabaseServer DataBaseInstanceName -DatabaseName "ContentDataBase"

This will restore a single site collection. But if we have to restore many site collections then running the above command every time will not be feasible & is a waste of time.
Now the way out in this situation is to prepare a Powershell script & run the script once & it will restore all the site collections we want. This Powershell script reads the site URL, backup name, DataBase Server name & Content DataBase Name from a csv file. We will enter the url's & their respective backup file names, Server Name & ContentDataBase name in the csv file type & give the path of the csv file in the script. This script now reads the values one by one from each row & restores the site collections.
When the rows are finished from the csv file then it stops the script. In this way we can restore large number of site collections by running a single command.

The Powershell script is as follows:

$backupfolder= "Path of Backup files"
$filePath = "Path of .csv file"
$csv_info = Import-Csv $filePath
$count =$csv_info.count
#iterate Csv File
foreach ($line in $csv_info)
{
$siteurl = $line.SiteUrl.trim()
$DatabaseInstance = $line.DatabaseInstance.trim()
$ContentDatabase = $line.ContentDatabase.trim()
$backuppath = $backupfolder + "\" + $line.BackupPath.trim()
#cls
Restore-SPSite -Identity $siteurl -Path $backuppath -Force -DatabaseServer $DatabaseInstance -DatabaseName $ContentDatabase
#Write-Host $siteurl
Write-Host $backuppath
Write-Host "Sucess"
}


Save the file with the .ps1 extension. e.g.- "restorescript.ps1".

Create a csv file & insert the entries as follows:


SiteUrl,BackupPath,DatabaseInstance,ContentDatabase
http://siteurl,siteurl.bak,InstanceName,WSS_Content_DBName
http://webapp/sites/siteurl2,siteurl2.bak,InstanceName,WSS_Content__DBName2
http://iconnectstaging/sites/siteurl3,siteurl3.bak,InstanceName,WSS_Content__DBName3
http://iconnectstaging/sites/siteurl4,siteurl4.bak,InstanceName,WSS_Content__DBName4


 When we have finished creating both the files, now open the Powershell Management tool & run a single command which contains only the path of the powershell script. e.g.- Restore-Path\restorescript.ps1.

The script will stop after all the site collection restoration is finished.

No comments:

Post a Comment