Skip to content

Instantly share code, notes, and snippets.

@wpsmith
Created March 31, 2015 19:27
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save wpsmith/0a20fe880fd6517ea6d4 to your computer and use it in GitHub Desktop.
Save wpsmith/0a20fe880fd6517ea6d4 to your computer and use it in GitHub Desktop.
PowerShell: SharePoint - Backup all site collections of my entire farm, be executable multiple times without overriding old backups, log all script results into a log file, remove backups older than X days, and execute on a daily basis.
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:
the user that executes the backup operation should have read/write permissions on the backup folder
the user that executes the backup operation should have enough permissions to execute a Backup-SPWeb operation
the script must be executed on a SharePoint server
You can download the script directly from the TechNet Script Center http://gallery.technet.microsoft.com/scriptcenter/Backup-all-collections-in-726514cb
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 the Program/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
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
@aneilg
Copy link

aneilg commented Feb 3, 2017

5 Star works brilliantly.

@Log2n77
Copy link

Log2n77 commented Sep 19, 2020

I am getting this error: "The given path's format is not supported."

@wpsmith
Copy link
Author

wpsmith commented Sep 22, 2020

I'm sorry. I don't write work in SharePoint anymore nor do I write PS scripts any longer either. Please feel free to fix and provide a patch if you have one.

@Log2n77
Copy link

Log2n77 commented Oct 8, 2020

Figured it out. I tested it on Dev with URLs containing port numbers. It was the ":" that was causing the error.
Works perfect

@wpsmith
Copy link
Author

wpsmith commented Oct 10, 2020

What line? Line 4?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment