Thursday, March 5, 2015

How to backup a site collection in Sharepoint using Powershell?


Add-PsSnapin Microsoft.SharePoint.PowerShell
Start-SPAssignment -Global            # This cmdlet takes care of the disposable objects to prevent memory leak.

$today=Get-Date -format "MM-dd-yyyy HH.mm.ss" # Get current date and format it to avoid invalid characters such as "/" and ":"

$mySite="http://site"     # Replace with your site collection URL

$backupLocation="c:\backup\$today"        # Replace with your backup location

$logFile="$backupLocation\BackupLog.log"    # Replace with your desired log file location
 #check if backup directory exist. if not create them.
    if (-not (Test-Path $backuplocation)) {
        New-Item $backuplocation -type directory
    }
write-Host Start backing up $mySite to $backupLocation
try
{
    # Create a new backup file and name it based on current date. If you want to create only 1 backup file and overwrite it each time the backup is run, you can replace "$today.bak" with your desired file name.
    Backup-SPSite -Identity $mySite -Path $backupLocation\$today.bak -force -ea Stop
    write-Host Backup succeeded.
  # Write success message to the log file
    write "$today    $mySite successfully backed up.">>$logFile   
}
catch        # If the process failed
{
    write-Host Backup failed. See $logFile for more information.
    # Write error message to the log file
    write "$today    Error: $_">>$logFile

}   
Stop-SPAssignment -Global
Remove-PsSnapin Microsoft.SharePoint.PowerShell
write-Host "Finished script."

  
    

No comments:

Post a Comment