SharePoint Online: Download All Versions of a Document using PowerShell

Requirement: Download All Versions of a Document in SharePoint Online using PowerShell

SharePoint Online: PowerShell to Download All Versions of a Document
Version history in SharePoint Online lets you to store, track, and restore files in a library as they are changed. There are times you may need to download all previous versions of a file. As downloading each version of a file is time-consuming and cumbersome from web UI, Here is the PowerShell to download all versions of a file from a SharePoint Online document library using CSOM.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Parameters
$SiteURL = "https://crescenttech.sharepoint.com"
$FileRelativeURL ="/Shared Documents/Discloser China.doc"
$DownloadPath= "C:\Temp"

#Get credentials to connect
$Cred = Get-Credential

#Setup the Context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName, $Cred.Password)
 
#Get the File and its versions
$File = $Ctx.Web.GetFileByServerRelativeUrl($FileRelativeURL)
$Ctx.Load($File)
$Ctx.Load($File.Versions)
$Ctx.ExecuteQuery()
 
If($File.Versions.Count -gt 0)
{
    Foreach($Version in $File.Versions)
    {
        #Frame File Name for the Version
        $VersionFileName = "$($DownloadPath)\$($Version.VersionLabel)_$($File.Name)"
        
        #Get Contents of the File Version
        $VersionStream = $Version.OpenBinaryStream()
        $Ctx.ExecuteQuery()

        #Create File version at local disk
        [System.IO.FileStream] $FileStream = [System.IO.File]::Open($VersionFileName,[System.IO.FileMode]::OpenOrCreate)
        $VersionStream.Value.CopyTo($FileStream)
        $FileStream.Close()
        
        Write-Host -f Green "Version $($Version.VersionLabel) Downloaded to :" $VersionFileName
    }
}
Else
{
    Write-host "No Versions Available for "$Item["FileRef"] -f Yellow
}
SharePoint Online: Download All Versions of a Document using PowerShell SharePoint Online: Download All Versions of a Document using PowerShell Reviewed by Salaudeen Rajack on June 17, 2018 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.