SharePoint Online: Get Document Library Size using PowerShell

Requirement: Get the Size of a SharePoint Online Document Library.

Get SharePoint Online Document Library Size using PowerShell

How to Check SharePoint Online Document Library Size?

Are you looking for a way to quickly find out the size of your document library in SharePoint Online? As document libraries grow and evolve, it is essential to monitor their size to ensure they use storage resources effectively and efficiently. In this article, we will explore how to determine the size of a document library in SharePoint Online, including a step-by-step guide to view a library’s total size and a breakdown of each folder and file within it. We’ll also see how to use PowerShell to get the size of your document library.

To get a Document library size, do the following: 

  1. Login to your SharePoint Online site >> Click on Settings >> Site Settings.
  2. Click on “Storage Metrics” under “Site Collection Administration”.
  3. The storage metrics page shows the size of each document library on the site under the “Total Size” column.
    sharepoint online get document library size

If you drill down, you will see the total size of the document library and a breakdown of the size of each folder and file in the library.

Please note that the size displayed in SharePoint Online may not be the exact size of the library on the file system, as SharePoint Online uses various techniques, such as compression and versioning, to optimize its data storage. However, the size displayed in SharePoint Online is a good estimate of the document library’s storage space.

You can also get the size of a document library from SharePoint Designer and Explorer view from properties of the document library.

PowerShell to Get List or Document Library Size in SharePoint Online:

Use this PowerShell script to get a library size in SharePoint Online:

#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"
   
#Function to Get the size of a List or Library in SharePoint Online
Function Get-SPOListSize($SiteURL, $ListName)
{ 
     Try
     {
        #Get credentials to connect to SharePoint Online
        $Cred = Get-Credential
 
        #Set up the context
        $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
        $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)
     
        #get the list
        $List = $Ctx.Web.Lists.GetByTitle($ListName)
        $Ctx.Load($List)
        $Ctx.ExecuteQuery()

        #Query to Get all List Items from all folders - exclude Folder objects
        $Query = New-Object Microsoft.SharePoint.Client.CamlQuery
        $Query.ViewXml = "<View Scope='RecursiveAll'><Query><OrderBy><FieldRef Name='ID' Ascending='TRUE'/></OrderBy></Query><RowLimit Paged='TRUE'>2000</RowLimit></View>" 
        $i=1;$TotalSize = 0
        Do {
            #Get items from the list in batches
            $ListItems = $List.GetItems($Query)
            $Ctx.Load($ListItems)
            $Ctx.ExecuteQuery()
            $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition

            ForEach($ListItem in ($ListItems| Where {$_.FileSystemObjectType -eq "File"}))
            {
                #Get the File
                $File = $ListItem.File
                $Ctx.Load($File)
                $Ctx.Load($File.Versions)
                $Ctx.ExecuteQuery()
                Write-host -f Yellow "Size of '$($File.Name)' Item ($i of $($List.ItemCount)) - " -NoNewline
 
                $FileSize =0; $VersionSize = 0
                If($File.Versions.Count -ge 1)
                {
                    $VersionSize = $File.Versions | Measure-Object -Property Size -Sum | Select-Object -expand Sum
                }
                $FileSize =  $ListItem.File.Length  + $VersionSize
                Write-host "$($ListItem.File.Length) + $VersionSize :" $FileSize
                $TotalSize += $FileSize
                $i++
                #Clear
            }
        } While ($Query.ListItemCollectionPosition -ne $null)
        Return [Math]::Round($TotalSize/1MB, 2)
    }
    Catch [System.Exception]
    {
        Write-Host -f Red "Error:"$_.Exception.Message
    }
}
   
#parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName="Branding"

#Call the function to get document library size
$LibrarySize = Get-SPOListSize -SiteURL $SiteURL -ListName $ListName
Write-host -f Green "`nToal Size of the list/library: $LibrarySize MB"

This can be useful if you need to know how much storage space your library is taking up.

PnP PowerShell to Get Document Library Size

We can also get the size of a document library using PnP PowerShell.

#Set Variables
$SiteURL = "https://crescent.sharepoint.com/sites/Marketing"
$LibraryName = "Documents"
 
#Connect to SharePoint Online site
Connect-PnPOnline -Url $SiteURL -Interactive

$FileData = @()
#Iterate through all files
Get-PnPListItem -List $LibraryName -PageSize 500 | Where {$_.FieldValues.FileLeafRef -like "*.*"} | ForEach-Object {
    Write-host "Getting Size of the File:"$_.FieldValues.FileRef -NoNewline
    #Get FileSize & version Size
    $FileSizeinKB = [Math]::Round(($_.FieldValues.File_x0020_Size/1KB),2)
    $File = Get-PnPProperty -ClientObject $_ -Property File
    $Versions = Get-PnPProperty -ClientObject $File -Property Versions
    $VersionSize = $Versions | Measure-Object -Property Size -Sum | Select-Object -expand Sum
    $VersionSizeinKB = [Math]::Round(($VersionSize/1KB),2)
    $TotalFileSizeKB = [Math]::Round(($FileSizeinKB + $VersionSizeinKB),2)
    Write-host `t $TotalFileSizeKB "KB" -f Yellow

    #extract File Size data
    $FileData+=New-Object PSObject -Property  ([Ordered]@{
        "File Name"  = $_.FieldValues.FileLeafRef
        "File URL" = $_.FieldValues.FileRef
        "File Size (KB)"  = $FileSizeinKB
        "Version Size (KB)"   = $VersionSizeinKB
        "Total File Size (KB)" = $TotalFileSizeKB
    })
}
$FileData | Format-table 
#Calculate the Total Size of the document library
$LibrarySize = [Math]::Round((($FileData | Measure-Object -Property "Total File Size (KB)" -Sum | Select-Object -expand Sum)/1KB),2)
Write-host -f Green "Total Library Size (MB):" $LibrarySize

Script output:

powershell to get document library size in sharepoint online

Find the size of all document libraries using PnP PowerShell

Here is another script to get the size of all document libraries in a site:

#Subsite URL
$SiteURL = "https://crescent.sharepoint.com/sites/Retail/Archived"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

# Initialize variable
$LibraryCounter = 0
$TotalSize = 0
$AllFiles = @()

# Get all document libraries in the subsite
$DocLibs = Get-PnPList | Where-Object {$_.BaseType -eq "DocumentLibrary" -and $_.Hidden -eq $False -and $_.Itemcount -gt 0 }
$TotalLibraries = $DocLibs.count

#Loop through each library
ForEach($Library in $DocLibs)
{
    # Display Progress bar
    Write-Progress -Activity "Processing Document Libraries" -Status "Scanning Document Library '$($Library.Title)'" -PercentComplete (($LibraryCounter / $TotalLibraries) * 100)

    #Get All Files from the library
    $AllFiles = Get-PnPListItem -List $Library -PageSize 2000 -Fields "SMTotalSize" | Where {$_.FileSystemObjectType -eq "File"}

    $LibrarySize = 0
    # Sum up File sizes
    ForEach ($File in $AllFiles) {
        $LibrarySize += $File["SMTotalSize"].LookupID
    }
    $LibrarySize = [Math]::Round($LibrarySize/1MB, 2)
    $TotalSize += $LibrarySize

    #Start-Sleep -Milliseconds 100
    $LibraryCounter++
}


# Return total size in MB
Write-host "Total size of the documents: $TotalSize MB" 

Get the document library size from Storage Metrics

Here is an alternative approach to find the list or document library size in SharePoint Online:

#Subsite URL
$SiteURL = "https://crescent.sharepoint.com/sites/Retail"

#Connect PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

#Get the current Web/subsite size
$LibrarySize = Get-PnPFolderStorageMetric -List "Documents" | Select -ExpandProperty TotalSize
$LibrarySize = [Math]::Round($LibrarySize/1MB, 2)
Write-host "Total size of the Library: $LibrarySize MB" 

Conclusion

In summary, determining the size of a document library in SharePoint Online is a straightforward process. By following the steps outlined above, you can easily view the total size of a library and get a breakdown of the size of each folder and file within it. This information helps monitor the growth of your document libraries and ensure they do not exceed their storage quotas. Additionally, You can use PowerShell to know the size of your document libraries, plan for future storage needs, and ensure that you have enough storage capacity to meet the demands of your organization.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

4 thoughts on “SharePoint Online: Get Document Library Size using PowerShell

  • Hi Salaudeen,

    Your articles are great and have saved lots of time for me.

    I have a DL with both folder and files and I am receiving the below error. “An error occurred while enumerating through a collection: The collection has not been initialized. It has not been requested or the request has not been executed. It may need to be explicitly requested..”. I was thinking this line of the script is failing for “folder” $File = Get-PnPProperty -ClientObject $_ -Property File.

    How do I get the size details of a DL which has multiple folders with sub-folders as well as files.

    Thanks,

    Reply
    • Did you ever resolve the error message that was being generated. I’m seeing the same error being generated, having incorporated this logic into a script that will run through all sites & site collections, but it seems to be sporadic rather than being generated for every file.

      This article from Salaudeen’s site, https://www.sharepointdiary.com/2018/07/sharepoint-online-fix-error-occurred-while-enumerating-through-collection-the-collection-has-not-been-initialized.html, suggests that “we have to use the Get-PnPProperty cmdlet to load a collection” to avoid this error, but that is what the example in this article is doing.
      @Salaudeen, any suggestions as to why this might not work every time?

      Reply
  • Thank you very much. The article helped me a lot.
    Have a nice day.

    Reply

Leave a Reply

Your email address will not be published. Required fields are marked *