kwizcom banner advertisement

SharePoint Online: Version History Report using PowerShell

Requirement: Generate version history report for all sites in a SharePoint site collection.
version history report for all libraries in sharepoint online using powershell

SharePoint Online PowerShell to Get Version History Details of a Document Library
#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"

#Set Parameters
$SiteURL="https://crescenttech.sharepoint.com/sites/marketing"
$LibraryName="Documents"
$ReportOutput = "C:\Temp\VersionHistory.csv"

Try {
    #Setup Credentials to connect
    $Cred= Get-Credential
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
 
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials
    
    #Get the web & Library
    $Web=$Ctx.Web
    $Ctx.Load($Web)
    $List = $Web.Lists.GetByTitle($LibraryName)
    $Ctx.ExecuteQuery()
        
    #Get All Files of from the document library - Excluding Folders
    $Query =  New-Object Microsoft.SharePoint.Client.CamlQuery
    $Query.ViewXml = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>0</Value></Eq></Where><OrderBy><FieldRef Name='ID' /></OrderBy></Query></View>"
    $ListItems=$List.GetItems($Query)
    $Ctx.Load($ListItems)
    $Ctx.ExecuteQuery()

    $VersionHistoryData = @()
    #Iterate throgh each version of file
    Foreach ($Item in $ListItems)
    {
        $File = $Web.GetFileByServerRelativeUrl($Item["FileRef"])
        $Ctx.Load($File)
        $Ctx.Load($File.ListItemAllFields)
        $Ctx.Load($File.Versions)
        $Ctx.ExecuteQuery()
        
        Write-host -f Yellow "Processing File:"$File.Name
        If($File.Versions.Count -ge 1)
        {
            #Calculate Version Size
            $VersionSize = $File.Versions | Measure-Object -Property Size -Sum | Select-Object -expand Sum
            If($Web.ServerRelativeUrl -eq "/")
            {
                $FileURL = $("{0}{1}" -f $Web.Url, $File.ServerRelativeUrl)
            }
            Else
            {
                $FileURL = $("{0}{1}" -f $Web.Url.Replace($Web.ServerRelativeUrl,''), $File.ServerRelativeUrl)
            }

            #Send Data to object array
            $VersionHistoryData += New-Object PSObject -Property @{
            'File Name' = $File.Name
            'Versions Count' = $File.Versions.count
            'File Size' = ($File.Length/1KB)
            'Version Size' = ($VersionSize/1KB)
            'URL' = $FileURL
            }
        }
    }
    #Export the data to CSV
    $VersionHistoryData | Export-Csv $ReportOutput -NoTypeInformation

    Write-host -f Green "Versioning History Report has been Generated Successfully!" 
}
Catch {
    write-host -f Red "Error Generating Version History Report!" $_.Exception.Message
}

PowerShell to Generate Version History Report for SharePoint Online Site Collection:
Here is the PowerShell to get version history of all files in document libraries in a SharePoint Online site collection.
#Import SharePoint Online module
Import-Module Microsoft.Online.SharePoint.Powershell

Function Generate-VersionHistoryReport()
{
  param
    (
        [Parameter(Mandatory=$true)] [string] $SiteURL,
        [Parameter(Mandatory=$true)] [string] $ReportOutput
    )
    Try {
        #Setup the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = $Credentials
        
        #Get all subsites and Lists from the site
        $Web = $Ctx.Web
        $Ctx.Load($Web)
        $Ctx.Load($Web.Webs)  
        $Lists = $Web.Lists
        $Ctx.Load($Lists)        
        $Ctx.ExecuteQuery()
        
        #Exclude system lists
        $ExcludedLists = @("Access Requests","App Packages","appdata","appfiles","Apps in Testing","Cache Profiles","Composed Looks","Content and Structure Reports","Content type publishing error log","Converted Forms",
            "Device Channels","Form Templates","fpdatasources","Get started with Apps for Office and SharePoint","List Template Gallery", "Long Running Operation Status","Maintenance Log Library", ,"Master Docs","Master Page Gallery"
               "MicroFeed","NintexFormXml","Quick Deploy Items","Relationships List","Reusable Content","Reporting Metadata", "Reporting Templates", "Search Config List","Site Assets", "Site Pages", "Solution Gallery",
                    "Style Library","Suggested Content Browser Locations","Theme Gallery", "TaxonomyHiddenList","User Information List","Web Part Gallery","wfpub","wfsvc","Workflow History","Workflow Tasks")

        
        Write-host -f Yellow "Processing Site: "$SiteURL
        $VersionHistoryData = @()

        #Iterate through each list in a site and get versioning configuration
        ForEach($List in $Lists)
        {
            if( ($ExcludedLists -NotContains $List.Title) -and ($List.EnableVersioning) -and ($List.BaseType -eq "DocumentLibrary"))
            {
                #Get All Files --Excluding Folders
                $Query =  New-Object Microsoft.SharePoint.Client.CamlQuery
                $Query.ViewXml = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FSObjType' /><Value Type='Integer'>0</Value></Eq></Where><OrderBy><FieldRef Name='ID' /></OrderBy></Query></View>"
                $ListItems=$List.GetItems($Query)
                $Ctx.Load($ListItems)
                $Ctx.ExecuteQuery()

                #Iterate throgh each version of file
                Foreach ($Item in $ListItems)
                {
                    $File = $web.GetFileByServerRelativeUrl($Item["FileRef"])
                    $Ctx.Load($File)
                    $Ctx.Load($File.Versions)
                    $Ctx.ExecuteQuery()

                        If($File.Versions.Count -ge 1)
                        {
                            $VersionSize=0 
                            #Calculate Version Size
                            Foreach ($Version in $File.Versions)
                            {
                                $VersionSize = $VersionSize + $Version.Size
                            }

                            #Send Data to object array
                            $VersionHistoryData += New-Object PSObject -Property @{
                            'Site' = $SiteURL
                            'Library' = $List.Title
                            'File Name' = $File.Name
                            'Version Count' = $FileVersions.count
                            'Version Size' = ($VersionSize/1024)
                            'URL' = $SiteURL+$File.ServerRelativeUrl
                            }
                        }
                }
            }
        }
        #Export the data to CSV
        $VersionHistoryData | Export-Csv $ReportOutput -Append -NoTypeInformation

        #Iterate through each subsite in the current web
        Foreach ($Subweb in $Web.Webs)
        {
            #Call the function recursively to process all subsites underneaththe current web
            Generate-VersionHistoryReport -SiteURL $Subweb.URL -ReportOutput $ReportOutput
        }
     }
    Catch {
        write-host -f Red "Error Generating version History Report!" $_.Exception.Message
    } 
}

#Set parameter values
$SiteURL="https://crescent.sharepoint.com"
$ReportOutput="C:\Temp\VersionHistory.csv"

#Get Credentials to connect
$Cred= Get-Credential
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

#Delete the Output report file if exists
if (Test-Path $ReportOutput) { Remove-Item $ReportOutput }

#Call the function to generate version History Report
Generate-VersionHistoryReport -SiteURL $SiteURL -ReportOutput $ReportOutput 

This script produces a CSV file with data such as:
  • Site 
  • Library 
  • File Name
  • Number of Versions
  • Version History Size
  • URL of the document
If you want to export individual version details such as: Version Label, Created by, comments, etc. use: SharePoint Online: Export List Version History to Excel using PowerShell
SharePoint Online: Version History Report using PowerShell SharePoint Online: Version History Report using PowerShell Reviewed by Salaudeen Rajack on December 14, 2016 Rating: 5

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.