So with any new SharePoint 2010 farm comes lots of powershell. Since we don’t have a nice 3rd party backup solution for granular backups setup yet, I decided to write a quick script that will get all site collecitons in all web applications and back them up.

The basic flow of the script is as follows:

  • create directory with current date for backup set
  • loop through all web apps
  • loop through all site collections
  • backup each site collection to a file using the site name as the file name
  • write site name and URL to sitemap.txt file so there is a location record

  • remove backups older than 30 days

#By Mike Tupker
#backups all site collections</p>

Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
Start-SPAssignment -Global

$today = Get-Date -format ""
$backuppath = "e:\backups\$today"
$logFile = "$backuppath\BackupLog.log"

    #check if backup directory exist. if not create them.
    if (-not (Test-Path $backuppath)) {
        New-Item $backuppath -type directory
    #loop through all web apps
    foreach ($webapp in Get-SPWebApplication) {
        #loop through all site in each web apps
        foreach ($site in Get-SPSite -WebApplication $webapp.url -Limit all | where {$_ -notlike "*Office_Viewing_Service_Cache"}) {
            #define backup name
            $name = $site.RootWeb.ToSTring() + ".bak"

            #backup site
            Write-Host Site URL: $site.Url
            Write-Host Site Name: $name
            Backup-SPSite -Identity $site.Url -Path $backupPath\$name -UseSqlSnapshot
            #create site map
            Write-Output "$name,$site.Url" | Out-File -FilePath $backupPath\siteMap.txt -Append

    #remove old backps older than 30 days
    $allbackups = Get-ChildItem e:\backups
    foreach($directory in $allbackups)
        $creationdate = ((Get-Date) - $directory.CreationTime).Days
        if ($creationdate -gt 30 -and $directory.PsISContainer -eq $True)

    write-Host Backup failed. See $logFile for more information.

    # Write error message to the log file
    write "$today    Error: $_">>$logFile

Stop-SPAssignment -Global` **Update 2011-11-14**: Changed loop for parsing site collections to exclude the office viewing service cache site. **Updated 2012-02-28:** changed code per comment.