PowerShell to restore *.cmp backup of SPWeb

Problem

I need to restore *.cmp file that contains SPWeb backup.

Solution

# Creating case sites and import backup files
# Created by Ben - 7 March 2019

Start-Transcript

clear
if ((gsnp "*sharepoint*" -ErrorAction SilentlyContinue) -eq $null){asnp *sharepoint*}

$caseSiteUrlUniquePattern = 'Exporting Web http://pacman' 
$truncateStart = '.intranet'
$targetSite = 'http://pacman-test'
$importLogFilename = 'Import.txt'
$currentPs1Filename = $MyInvocation.MyCommand.Name
$currentPs1FilePath = $MyInvocation.MyCommand.Definition
$backupFolder = $currentPs1FilePath.SubString(0,$currentPs1FilePath.indexOf($currentPs1Filename))
$importLogFilePath = $backupFolder + $importLogFilename
$processedFolder = $backupFolder+'Restored\'

if(!(Test-Path $importLogFilePath)) {
    New-item -Path $backupFolder -Name $importLogFilename -ItemType 'file'
}
    
Get-ChildItem $backupFolder -Filter *.log | 
Foreach-Object {
    $cmpLogFilePath = $_.FullName
    $backupFilePath = $_.FullName.SubString(0,$_.FullName.length-4) + '.cmp'
    $cmpImportLogFilePath = $_.FullName.SubString(0,$_.FullName.length-4) + '.cmp.import.log'
    $content = Get-Content $_.FullName
    #find file content that match the specific pattern
    $content | Where-Object {$_ -match $caseSiteUrlUniquePattern} | Foreach-Object {
        #extract the case site url 
        $webUrl = $targetSite + $_.SubString($_.indexOf($truncateStart),$_.length-$_.indexOf($truncateStart)-1)
        Write-Host Creating $webUrl
        $web = New-SPWeb -Url $webUrl
        if($web){
            Add-Content -Path $importLogFilePath -Value $($(Get-Date -Format g) + ': Created ' + $web.url)
            Write-Host Importing $backupFilePath to $web.Url
            Import-SPWeb -Identity $web.Url -Path $backupFilePath -IncludeUserSecurity
            Add-Content -Path $importLogFilePath -Value $($(Get-Date -Format g) + ': Imported backup file ' + $backupFilePath + ' to ' + $web.url)
            Move-Item -Path $cmpLogFilePath -Destination $processedFolder
            Move-Item -Path $backupFilePath -Destination $processedFolder
            Move-Item -Path $cmpImportLogFilePath -Destination $processedFolder
        }
    } 
}

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