Thursday, September 18, 2014

Using the SPImport events to control SharePoint content import


The SPImport class in the Microsoft.SharePoint.Deployment namespace participates with other classes in the Deployment namespace to support importing, publishing, and migrating Windows SharePoint content, as well as supporting restore capabilities of content.
You can initiate an import operation by first initializing an instance of the Microsoft.SharePoint.Deployment.SPImportSettings class with the required import settings, and then passing the SPImportSettings object to the constructor of SPImport class; you then call the SPImport.Run method. The SPImport type exposes events that can be used to control the process of import. You can utilize the event model in PowerShell to register the events and then make use of this information to control the complete process of importing and exporting SharePoint content. Below is the PowerShell snippet to use the Error event and use the data to fail the execution process after an Import is performed.

$Global:importErrors = @()
$Global:importWarnings = @()  

try{      
     Register-ObjectEvent -InputObject $SPImport -EventName Error -SourceIdentifier Microsoft.SharePoint.Deployment.SPDeployment.Error -Action {
           $arguments = $event.SourceEventArgs
           if(($arguments.ErrorType -eq [Microsoft.SharePoint.Deployment.SPDeploymentErrorType]::Error) -or ($arguments.ErrorType -eq [Microsoft.SharePoint.Deployment.SPDeploymentErrorType]::FatalError)){
                $Global:importErrors += $arguments.ErrorMessage

           }
           if($arguments.ErrorType -eq [Microsoft.SharePoint.Deployment.SPDeploymentErrorType]::Warning){
                $Global:importWarnings += $arguments.ErrorMessage
           }

     } | Out-Null

     $SPImport.Run()
}
finally{

     Unregister-Event -SourceIdentifier Microsoft.SharePoint.Deployment.SPDeployment.Error -ErrorAction SilentlyContinue

} 

if($Global:importWarnings.Length -gt 0){
     Write-Warning ("SPImport generated {0} warnings during import process. Please refer to the SP-Import log file {1} for more details." -f $Global:importWarnings.Length, $logFile)
}

if($Global:importErrors.Length -gt 0){
     Write-Warning ("The below given errors were generated during import process. Please refer to the SP-Import log file {0} for more details." -f $logFile)
     $Global:importErrors | select -Unique | ForEach-Object {
           Write-Host $_
     }

     Write-Error ("SPImport failed with {0} errors during import process. The details of errors can be found in the SP-Import log file {1}" -f $Global:importErrors.Length, $logFile)
}

Write-Host ("SPImport process completed without errors. Please refer to the SP-Import log file {0} for more details" -f $logFile) -ForegroundColor Green

No comments: