PowerShell to backup SPWeb and its children

Problem

In line with previous article I wrote about restoring SPWeb backup using PowerShell script, I've written another one to perform backup of SPWeb and children.

Solution

# Created by Ben - 7 March 2019
# PowerShell script to export SPWeb and nested SPWebs ($webUrlPattern) to $exportToFolder
# -IncludeVersions 4 = All versions for files and list items
#                  3 = Last major and last minor version for files and list items
#                  2 = The current version, either the last major version or the last minor version
#                  1 = Last major version for files and list items (default)
# Supported by SharePoint 2010, 2013, 2016, 2019
# Note: this script can be adjusted to support SPSite or SPList

Start-Transcript

clear
$startTime = (Get-Date)

$exportToFolder = 'Exported' + $startTime.ToString("yyyyMMdd-HHmmss")
$webUrl = "http://your-site-url/cases"
$webUrlPattern = $webUrl+'/..../'

$currentPs1Filename = $MyInvocation.MyCommand.Name
$currentPs1FilePath = $MyInvocation.MyCommand.Definition
$currentPs1FileFolder = $currentPs1FilePath.SubString(0,$currentPs1FilePath.indexOf($currentPs1Filename))
$exportToFolderPath = $currentPs1FileFolder + $exportToFolder + '\'

if(!(Test-Path $exportToFolderPath)) {
    Write-Host Creating new folder $exportToFolderPath
    New-item -Path $currentPs1FileFolder -Name $exportToFolder -ItemType 'directory'    
}

if ((gsnp "*sharepoint*" -ErrorAction SilentlyContinue) -eq $null){asnp *sharepoint*}
$web = Get-SPWeb -Identity $webUrl
$counter = 0

$web.site.allwebs | ?{$_.url -match $webUrlPattern} | ?{
    $counter +=1
    $cmpFilePath = $exportToFolderPath + $_.id.ToString() + '.cmp'
    Write-Host Exporting $_.url to $cmpFilePath
    Export-SPWeb -Identity $_.url -Path $cmpFilePath -IncludeVersions 4 -IncludeUserSecurity -Force
}

Write-Host Total number of SPWeb exported: $counter
Write-Host Duration: ((Get-Date) - $startTime).TotalMinutes minutes

Stop-Transcript

Explanation

I hope it's self-explanatory. If not, please leave some comments and I'll write more about it. Thanks.

Comments

Popular posts from this blog

How to rename your tenancy hostname of SharePoint Online (sharepoint.com)

How to migrate SharePoint Online SPWeb with custom SPList form (PowerApps) and Flows