Monday, April 25, 2011

SP2010 : Backup Restore with Powershell

Scenario:
I have to do this often for my client. While working on SPD , things can get screwed and so I need a quick backup's at different stages.

Also In case I am screwed I want to recover from my latest backup quickly.

Solution:
Powershell, yes :)

How it works:
1. Create a folder where you want to maintain your backups
2. Copy the backup.ps1 and restore.ps1 in same folder.
3. Make sure you have the right site collection url , its hard-coded but can be parameterized but then it will not be fast ;)
4. Keep the PS Command open and run backup / restore scripts as you want.

Backup.ps1:

$siteCollUrl = "http://intranet.contoso.com/"

$a = Get-Date
$currentfolder = (Get-Location -PSProvider FileSystem).ProviderPath

$filename = $currentFolder + "\backup_" + $a.Day.ToString() + "." + $a.Month.ToString() + "." + $a.Year.ToString() + "." + $a.Hour.ToString() + "." + $a.Minute.ToString() + "." + $a.Second.ToString() + ".bak"

Backup-SPSite $siteCollUrl -Path $filename
Restore.ps1:
$siteCollUrl = "http://intranet.contoso.com/"

$currentfolder = (Get-Location -PSProvider FileSystem).ProviderPath
$collFiles = @(gci $currentfolder | Where-Object {$_.name -like "backup_*"})

if($collFiles.Count -gt 0 )
{
$objFile = $collFiles | Select-Object -Last 1;
$filename = $objFile.FullName
Restore-SPSite $siteCollUrl -Path $filename -force
}
else
{
Write-Host "No backup to restore"
}

0 comments: