ویرایش:1394/08/30 06:22 ب.ظ
Picture Placeholder: mostafa rafiei
Picture Placeholder: mostafa rafiei
  • mostafa rafiei

Using PowerShell to backup all site collections in a SharePoint 2010/2013 farm

One of my requirements was to create a script that backups all my site collections in a development environment.

Backups and script requirements

Backing up and restoring a SharePoint environment can be done in different ways. The choice for the backup strategy depends on granularity one would like to achieve (and naturally also the expenses). There are some of the ways of backing up SharePoint:

  • Central Admin backup options
  • SQL Server back up of databases
  • Third party tools
  • PowerShell

The Central admin option improved quite a bit from the last version, nevertheless, it is a good choice when you need to do manual work. SQL Server is good if you want to backup whole content databases. Third party tools come into play due to their granularity and automatisms. However, these solutions are too costly and oversized for my purpose here. I wanted a solution that is more customizable and automated. Therefore, the last option was to write a PowerShell script that creates a backup of each single site collection in my farm. The requirements for this script are:

  1. backup all site collections of my entire farm
  2. execute multiple times a backup without overriding the old backups
  3. log all script results in a log file
  4. remove backups that are older than x days
  5. execute the backups on a daily basis

The script

According to the requirements above, the resulting script looks as follows:

Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

# specify here your backup folder
$backupRoot = "C:ScriptingBackup"
$logPath = Join-Path $backupRoot "_logs"
$tmpPath = Join-Path $backupRoot "_tmp"
# removes all the old backup files on the target folder (valid values: 0 = do not remove; 1 = remove files
$clearUpOldFiles = 0
# specifies the days for the backups that should be persisted
$removeFilesOlderThanDays = -1
# specifies the backupfolder based on the current weekday (Monday... etc.)
$todaysBackupFolder = Join-Path $backupRoot ((Get-Date).DayOfWeek.toString())

# generate all necessary folders if they are missing
if (-not (Test-Path $logPath)) {
  New-Item $logPath -type directory
}

if (-not (Test-Path $tmpPath)) {
  New-Item $tmpPath -type directory
}

if (-not (Test-Path $todaysBackupFolder)) {
  New-Item $todaysBackupFolder -type directory
}

# creates a log file
Start-Transcript -Path (Join-Path $logPath ((Get-Date).ToString('yyyyMdd_hhmmss') + ".log"))

# loop over all web applications (specify filter criteria here if you want to filter them out)
foreach ($webApplication in Get-SPWebApplication) {
    Write-Host
    Write-Host
    Write-Host "Processing $webApplication"
    Write-Host "*******************************"

    foreach ($site in $webApplication.Sites) {
        # we have to replace some characters from the url name
        $name = $site.Url.Replace("http://", "").Replace("https://", "").Replace("/", "_").Replace(".", "_");
        # replace all special characters from url with underscores
        [System.Text.RegularExpressions.Regex]::Replace($name,"[^1-9a-zA-Z_]","_");

        # define the backup name
        $backupPath = Join-Path $tmpPath ($name + (Get-Date).ToString('yyyyMdd_hhmmss') + ".bak")

        Write-Host "Backing up $site to $backupPath"
        Write-Host

        # backup the site
        Backup-SPSite -Identity $site.Url -Path $backupPath
    }

    Write-Host "*******************************"
    Write-Host "*******************************"
}

Write-Host
Write-Host

# remove the old backup files in the todays folder if specified
if ($clearUpOldFiles -eq 1) {
  Write-Host "Cleaning up the folder $todaysBackupFolder"
  Remove-Item ($todaysBackupFolder + "*")
}

# move all backup files from the tmp folder to the target folder
Write-Host "Moving backups from $tmpPath to $todaysBackupFolder"
Move-Item -Path ($tmpPath + "*") -Destination $todaysBackupFolder
# you can specify an additial parameter that removes filders older than the days you specified

if ($removeFilesOlderThanDays -gt 0) {

  Write-Host "Checking removal policy on $todaysBackupFolder"

  $toRemove = (Get-Date).AddDays(-$removeFilesOlderThanDays)

  $filesToRemove = Get-ChildItem $todaysBackupFolder -Recurse -Include "*.bak" | Where {$_.LastWriteTime -le “$toRemove” }

  if ($filesToRemove -ne $null) {

    foreach ($fileToRemove in $filesToRemove)  {

      Write-Host "Removing the file $fileToRemove because it is older than $removeFilesOlderThanDays days"

      Remove-Item $fileToRemove

    }

  }

}

Stop-Transcript
1
 

The script logic is pretty straightforward. Please change these script variables to your environment accordingly:

  • $backupRoot = “C:ScriptingBackup”: specify the backup location for the backup files and log files.
  • $clearUpOldFiles = 0: remove the old backups of the given weekday
  • $removeFilesOlderThanDays = –1: remove all backup files of the current weekday if they are older than x days (–1 means disabled).

You can leave the rest untouched. Basically, the script version above executes the following logic:

  • get the weekday and create a backup folder (if it does not exist) in the $backupRoot
  • loop over all web applications
    • loop over all sites of the current web application
      • get a unique backup name for the current site
      • execute the Backup-SPWeb operation for the given site and store it into a _tmp folder
  • if the variable $clearUpOldFiles = 1, then clear up the existing weekday folder
  • move the backups from _tmp to the weekday folder
  • if $removeFilesOlderThanDays > 0, then check if there are files in the weekday folder that are older than x days. Remove them if you found any.
  • store the log into the “_log” folder that resides in the $backupRoot

The script automatically creates all necessary files and folders. Anyway, we have to ensure following if we want to execute successfully this script:

But we did not cover all requirements!

With the script above we are able to cover requirements 1 to 4. You can execute the script manually as many times you want. The backup names are unique and allow you to do this as many times you want. You can even play around with the variables $clearUpOldFiles and $removeFilesOlderThanDays to keep your disk a little bit under control. Nevertheless, we also want to conver requirement 5 and automate the whole story. We only need to create a scheduled task on our Windows Server. The next screens tell you how to do this:

  • go to the server manager of your Windows Server 2008 and go under Configuration –> Task Scheduler
  • press Create Task… on the right side of the screen. You should see screen that follows. I gave to the task the name PowerShell Backup Script,selected Run whether user is logged on or not and ensured that the user that runs the task has enough privileges to write to the backup folder and execute the Backup-SPWeb operation (in my case I selected the SharePoint farm administrator – spowner).
  • I went to the Triggers tab and clicked the button New…. I configured the schedule from Monday to Friday and pressed OK.
  • I went to the Actions tab and clicked the button New…. I copied following execution path: C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -NoLogo -NonInteractive -File “C:ScriptingBackupExecuteBackup.ps1″ into theProgram/Script section. Please change the path in bold to your backup destination. Confirm with OK
  • Another window opens. Just confirm.

Store the script and we are done. Requirement 5 is covered with the scheduled task. You can still execute the script directly from file system or by executing it directly from the Task Scheduler window

Summary

This blog post described a PowerShell script that is backing up all site collections in a farm. Feel free to use this script and change it to your needs. Please note that this script is not intended for production environments. Nevertheless, it shows that you can achieve good results with a little bit of PowerShell skills.

Picture Placeholder: mostafa rafiei
  • mostafa rafiei
/_layouts/15/images/person.gif" alt="Picture Placeholder: mostafa rafiei" />
mostafa rafiei

One of my requirements was to create a script that backups all my site collections in a development environment.

Backups and script requirements

Backing up and restoring a SharePoint environment can be done in different ways. The choice for the backup strategy depends on granularity one would like to achieve (and naturally also the expenses). There are some of the ways of backing up SharePoint:

  • Central Admin backup options
  • SQL Server back up of databases
  • Third party tools
  • PowerShell

The Central admin option improved quite a bit from the last version, nevertheless, it is a good choice when you need to do manual work. SQL Server is good if you want to backup whole content databases. Third party tools come into play due to their granularity and automatisms. However, these solutions are too costly and oversized for my purpose here. I wanted a solution that is more customizable and automated. Therefore, the last option was to write a PowerShell script that creates a backup of each single site collection in my farm. The requirements for this script are:

  1. backup all site collections of my entire farm
  2. execute multiple times a backup without overriding the old backups
  3. log all script results in a log file
  4. remove backups that are older than x days
  5. execute the backups on a daily basis

The script

According to the requirements above, the resulting script looks as follows:

Add-PSSnapin Microsoft.SharePoint.Powershell -ErrorAction SilentlyContinue

# specify here your backup folder
$backupRoot = "C:ScriptingBackup"
$logPath = Join-Path $backupRoot "_logs"
$tmpPath = Join-Path $backupRoot "_tmp"
# removes all the old backup files on the target folder (valid values: 0 = do not remove; 1 = remove files
$clearUpOldFiles = 0
# specifies the days for the backups that should be persisted
$removeFilesOlderThanDays = -1
# specifies the backupfolder based on the current weekday (Monday... etc.)
$todaysBackupFolder = Join-Path $backupRoot ((Get-Date).DayOfWeek.toString())

# generate all necessary folders if they are missing
if (-not (Test-Path $logPath)) {
  New-Item $logPath -type directory
}

if (-not (Test-Path $tmpPath)) {
  New-Item $tmpPath -type directory
}

if (-not (Test-Path $todaysBackupFolder)) {
  New-Item $todaysBackupFolder -type directory
}

# creates a log file
Start-Transcript -Path (Join-Path $logPath ((Get-Date).ToString('yyyyMdd_hhmmss') + ".log"))

# loop over all web applications (specify filter criteria here if you want to filter them out)
foreach ($webApplication in Get-SPWebApplication) {
    Write-Host
    Write-Host
    Write-Host "Processing $webApplication"
    Write-Host "*******************************"

    foreach ($site in $webApplication.Sites) {
        # we have to replace some characters from the url name
        $name = $site.Url.Replace("http://", "").Replace("https://", "").Replace("/", "_").Replace(".", "_");
        # replace all special characters from url with underscores
        [System.Text.RegularExpressions.Regex]::Replace($name,"[^1-9a-zA-Z_]","_");

        # define the backup name
        $backupPath = Join-Path $tmpPath ($name + (Get-Date).ToString('yyyyMdd_hhmmss') + ".bak")

        Write-Host "Backing up $site to $backupPath"
        Write-Host

        # backup the site
        Backup-SPSite -Identity $site.Url -Path $backupPath
    }

    Write-Host "*******************************"
    Write-Host "*******************************"
}

Write-Host
Write-Host

# remove the old backup files in the todays folder if specified
if ($clearUpOldFiles -eq 1) {
  Write-Host "Cleaning up the folder $todaysBackupFolder"
  Remove-Item ($todaysBackupFolder + "*")
}

# move all backup files from the tmp folder to the target folder
Write-Host "Moving backups from $tmpPath to $todaysBackupFolder"
Move-Item -Path ($tmpPath + "*") -Destination $todaysBackupFolder
# you can specify an additial parameter that removes filders older than the days you specified

if ($removeFilesOlderThanDays -gt 0) {

  Write-Host "Checking removal policy on $todaysBackupFolder"

  $toRemove = (Get-Date).AddDays(-$removeFilesOlderThanDays)

  $filesToRemove = Get-ChildItem $todaysBackupFolder -Recurse -Include "*.bak" | Where {$_.LastWriteTime -le “$toRemove” }

  if ($filesToRemove -ne $null) {

    foreach ($fileToRemove in $filesToRemove)  {

      Write-Host "Removing the file $fileToRemove because it is older than $removeFilesOlderThanDays days"

      Remove-Item $fileToRemove

    }

  }

}

Stop-Transcript
1
 

The script logic is pretty straightforward. Please change these script variables to your environment accordingly:

  • $backupRoot = “C:ScriptingBackup”: specify the backup location for the backup files and log files.
  • $clearUpOldFiles = 0: remove the old backups of the given weekday
  • $removeFilesOlderThanDays = –1: remove all backup files of the current weekday if they are older than x days (–1 means disabled).

You can leave the rest untouched. Basically, the script version above executes the following logic:

  • get the weekday and create a backup folder (if it does not exist) in the $backupRoot
  • loop over all web applications
    • loop over all sites of the current web application
      • get a unique backup name for the current site
      • execute the Backup-SPWeb operation for the given site and store it into a _tmp folder
  • if the variable $clearUpOldFiles = 1, then clear up the existing weekday folder
  • move the backups from _tmp to the weekday folder
  • if $removeFilesOlderThanDays > 0, then check if there are files in the weekday folder that are older than x days. Remove them if you found any.
  • store the log into the “_log” folder that resides in the $backupRoot

The script automatically creates all necessary files and folders. Anyway, we have to ensure following if we want to execute successfully this script:

But we did not cover all requirements!

With the script above we are able to cover requirements 1 to 4. You can execute the script manually as many times you want. The backup names are unique and allow you to do this as many times you want. You can even play around with the variables $clearUpOldFiles and $removeFilesOlderThanDays to keep your disk a little bit under control. Nevertheless, we also want to conver requirement 5 and automate the whole story. We only need to create a scheduled task on our Windows Server. The next screens tell you how to do this:

  • go to the server manager of your Windows Server 2008 and go under Configuration –> Task Scheduler
  • press Create Task… on the right side of the screen. You should see screen that follows. I gave to the task the name PowerShell Backup Script,selected Run whether user is logged on or not and ensured that the user that runs the task has enough privileges to write to the backup folder and execute the Backup-SPWeb operation (in my case I selected the SharePoint farm administrator – spowner).
  • I went to the Triggers tab and clicked the button New…. I configured the schedule from Monday to Friday and pressed OK.
  • I went to the Actions tab and clicked the button New…. I copied following execution path: C:WindowsSystem32WindowsPowerShellv1.0powershell.exe -NoLogo -NonInteractive -File “C:ScriptingBackupExecuteBackup.ps1″ into theProgram/Script section. Please change the path in bold to your backup destination. Confirm with OK
  • Another window opens. Just confirm.

Store the script and we are done. Requirement 5 is covered with the scheduled task. You can still execute the script directly from file system or by executing it directly from the Task Scheduler window

Summary

This blog post described a PowerShell script that is backing up all site collections in a farm. Feel free to use this script and change it to your needs. Please note that this script is not intended for production environments. Nevertheless, it shows that you can achieve good results with a little bit of PowerShell skills.

01394/08/30 06:21 ب.ظ1394/08/30 06:22 ب.ظخیرAdministration
0
1393/10/23 07:08 ب.ظ
گفتمانی برای نمایش وجود ندارد