🎉 Our Microsoft 365 Reporting & Management Tool is now available in Azure Marketplace 🚀
This website uses cookies to improve your experience. We'll assume you're ok with this. Know more.
SharePoint Online

How to Find the File and Subfolder Count in a SharePoint Document Library

Imagine your organization manages a large SharePoint Online document library, with multiple departments adding files to various subfolders. As the volume grows, keeping things organized and accessible becomes more challenging. Therefore, monitoring file and subfolder counts helps maintain structure and identify libraries that may need cleanup. This guide shows how to get file and subfolder counts in each SharePoint document library folder for better management.

Count Files and Subfolders in SharePoint Document Library Folders

Microsoft 365 Permission Required
Site Member Least Privilege
Global Admin Most Privilege
  • In a SharePoint Online site, navigate to the desired document library and click Add column from the column header.
  • Click Show or hide columns, then in the Edit view columns panel, check the boxes for Item Child Count and Folder Child Count.
  • Click Apply to see the Item Child Count and Folder Child Count columns included along with the existing columns. These will show the number of files and subfolders in each folder.
Count Files and Subfolders in SharePoint Document Library Folders
  • Note: After adding the columns, they will be visible across all nested folders. You can then navigate to any folder to view the number of files and subfolders it contains.

Retrieve Document Library File and Subfolder Count Using PowerShell

Microsoft 365 Permission Required
Site Member Least Privilege
Global Admin Most Privilege
  • The above approach helps you view file and subfolder counts within a document library or its folders. However, it requires navigating through each nested level to see the details.
  • To simplify this, you can use PowerShell to get file and subfolder counts from all nested levels at once.
  • To do so, first connect to the SharePoint Online site using PnP PowerShell (requires PowerShell 7 or above) with the following cmdlet.
  • Windows PowerShell Windows PowerShell
     Connect-PnPOnline -Url "<SiteURL>" -ClientId "<ClientID>" 
  • If you haven't set up a Microsoft Entra ID app to connect to SharePoint Online using the PnP module, you can create one using this cmdlet.
  • Windows PowerShell Windows PowerShell
       Register-PnPEntraIDAppForInteractiveLogin  -ApplicationName  "<AppName>" -Tenant  "<TenantName>.onmicrosoft.com" 
  • After you connect, run the cmdlet after replacing <LibraryName> and <OutputPath/Name> to retrieve the file and subfolder counts for each folder in the specified document library.
  • Windows PowerShell Windows PowerShell
     Get-PnPListItem -List "<LibraryName>" | Where-Object { $_.FileSystemObjectType -eq "Folder" } | 
    ForEach-Object { 
          Get-PnPProperty -ClientObject $_.Folder -Property Files, Folders | Out-Null 
       	$depth = ($_.FieldValues.FileRef -split '/').Count - 5 
           [pscustomobject]@{ 
               Folder      = (' ' * ($depth * 4)) + $_.FieldValues.FileLeafRef 
              Path        = $_.FieldValues.FileRef 
               Files       = $_.Folder.Files.Count 
               SubFolders  = $_.Folder.Folders.Count 
          }
    } | Sort-Object Path | 
    Export-Csv -Path "<OutputPath/Name.csv>" -NoTypeInformation 
Retrieve Document Library File and Subfolder Count Using PowerShell

Gain Deeper File and Folder Insights in SharePoint Online!

AdminDroid’s SharePoint Online reporting tool simplifies the process of managing document libraries by offering detailed reports on file and folder counts. It keeps you updated on the structure of your document libraries, so you can maintain a secure and well-organized SharePoint Online environment.

Monitor SharePoint File Activity with Detailed Insights

Leverage the SharePoint Online file activities report to gain deep insights into specific actions such as file access, uploads, deletions, moves, and downloads, all in one place.

Track Folder Activities in SharePoint Online

Check folder-level activities in SharePoint Online to gain essential insights into folder access, modifications, and movements for better data integrity control.

Analyze SharePoint Site Content Overview

Utilize the SharePoint site content overview report to get instant visibility into details like total file and folder count along, with sharing insights.

Review Inactive SharePoint Libraries

Analyze the SharePoint inactive library report and delete unused libraries to keep the environment organized and ensure efficient use of storage.

Identify Document Libraries with No Versioning

Review document libraries without versioning and enable versioning on essential ones to retain file history, monitor changes, and prevent data loss during updates.

Inspect Information Rights Management Enabled SPO Document Libraries

Verify IRM-enabled document library to identify any sensitive libraries lacking protection and ensure data security by checking the expiration and rejection status of each IRM-enabled document library.

Overall, AdminDroid’s SharePoint Online management tool provides visibility into document library content overviews, file and folder permissions, sharing activity, and usage trends. With advanced reporting and auditing capabilities, it supports proactive management, strengthens data security, and ensures better control over SharePoint Online.

Explore a full range of reporting options

Important Tips

Use document sets in SPO to minimize load on the top-level view and prevent exceeding the list view threshold, as it counts as a single item.

Create custom views in SharePoint document library to keep important files and folders easily accessible, without the need to sort or filter every time.

Configure content approvals in SharePoint document libraries to ensure that only approved files and folders are visible to other users for broader access.

Common Errors and Resolution Steps

Below are some possible errors you may encounter while retrieving or working with files and subfolders in a SharePoint Online document library.

Error Register-PnPManagementShellAccess: Specified method is not supported.

This error occurs in PowerShell when you try to register an app to connect to SharePoint Online using the method' Register-PnPManagementShellAccess', which is no longer supported.

Fix Use the 'Register-PnPEntraIDAppForInteractiveLogin' cmdlet to register an app for interactive login with delegated access.

Error Connect-PnPOnline: Specified method is not supported.

This error occurs when you try to connect to PnP PowerShell without providing a client ID.

Fix To fix this, create and register an app in Microsoft Entra, and use its application ID/client ID when establishing the connection.
Connect-PnPOnline -Url "<SiteUrl>" -ClientId "<ClientID>" 

Error Get-PnPListItem: You are not signed in. Please use Connect-PnPOnline to connect.

This error occurs in PowerShell because no active connection to your SharePoint Online has been established.

Fix To resolve this, connect to SharePoint Online using your registered Entra ID app's Client ID:
Connect-PnPOnline -Url "<SiteURL>" -ClientId "<ClientID>" 
//Alternatively, to connect to SharePoint Online using certificate credentials with the registered Entra app:
Connect-PnPOnline –Url "<SiteURL>" -TenantName "<TenantName>.onmicrosoft.com" -ClientId "<ClientId>" -CertificateThumbprint "<CertThumbprint>" -URL "<SiteURL>"

Error Get-PnPListItem: List ‘<LibraryName>’ does not exist at site with URL.

This error occurs because the specified document library does not exist at the given SharePoint Online site URL.

Fix To resolve this, verify that the document library name is correct and it exists at the specified site URL.

Error The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.

This error occurs when you perform certain tasks, such as filtering, sorting, or grouping, on large libraries that exceed the 5,000-item view threshold.

Fix Move files and folders to separate document libraries and index relevant columns to prevent this issue in the future.

Error The specified file or folder name is too long. The URL path for all files and folders must be 400 characters or less (and no more than 400 characters for any single file or folder name in the URL). Please type a shorter file or folder name.

This error occurs when the server-relative URL exceeds the 400-character due to the name of the SharePoint Online file, folder, or document library.

Fix To resolve this error, use short names for folders or files, and limit the number of nested folders to reduce the total path length.
Frequently Asked Questions

Effectively Analyze and Manage SharePoint Document Library Files and Folders

1. How to get the total number of nested files and folders in each SharePoint document library?

The methods listed above help retrieve the count of first-level files and folders in a SharePoint document library or folder. While this is useful for analyzing top-level content, counting all files and folders, including those in nested levels, helps manage library performance more effectively.

Since native methods fall short in this regard, we’ve developed a PowerShell script. It exports a list of all document libraries in SharePoint Online, along with details such as the total file and folder count.

Retrieve the total number of files and folders in SharePoint document libraries

  • Download and execute the script to export the total count of nested files and folders from SharePoint Online document libraries.
  • The exported CSV contains details such as total file and folder counts, library details, size details, etc.
sharepoint-document-library-report-powershell

No more PowerShell hassles! AdminDroid lets you instantly view detailed counts of all nested files and folders in each document library.

  • With the document library content overview report, you can see how many files and folders are nested in a SharePoint library.
  • Click on the interlink associated with the file or folder count to quickly view detailed information about the respective contents.
admindroid-document-library-content-overview

Pro Tip💡: Utilize the Explore full report option found at the top of the quick view to see the details as a dedicated report and to export it.

2. Why is it important to find the file and subfolder counts in each folder of a SharePoint document library?

Finding files and subfolder count in each folder of a SharePoint document library is essential for the following reasons:

Library scalability and structure

  • It provides visibility into how a specific library or folder expands over time and helps identify when it is approaching SharePoint’s 5,000-item threshold per view.
  • By observing these counts, you can identify the fastest-growing libraries and reconstruct the existing contents into smaller folders.
  • Understanding the structure of files and subfolders is essential for maintaining a clean and organized library. It enables administrators to avoid clutter, reduce duplication, and streamline navigation.

Data validation and governance

  • It helps spot unexpected issues like missing files, duplicates, or failed uploads, especially in environments with frequent syncs or third-party integration periods.
  • File and subfolder count is crucial during migrations and bulk imports, as it serves as a critical checkpoint.

3. What happens when a SharePoint document library exceeds the list view threshold?

When a SharePoint Online document library exceeds 5,000 items, performance issues may occur. Users might experience delays or errors while trying to access or interact with the library.

This is due to the list view threshold. It does not limit how many items you can store in total. A single library can hold up to 30 million items. However, it limits how many items can be retrieved or displayed in one view or query unless indexed columns are used.

Note: The 5,000-item threshold is not always fixed. It can vary depending on your site’s configuration, database activity, and overall usage.

Once the SharePoint list view threshold limit is crossed:

  • Views that lack proper indexing or filters may fail to load. Sort or filter functions may not work consistently.
  • Flows, custom apps, and scripts may time out or return incomplete data.
  • Users may see errors like ‘The attempted operation is prohibited because it exceeds the list view threshold’.

How to overcome SharePoint list view threshold?

  • Apply filters or use indexed columns to ensure the view works within the 5,000-item threshold.
  • Break content into small folders and organize documents by year, department, or project to manage large lists effectively.
  • Monitor item growth proactively (e.g., using tools like Power Automate, PowerShell).

Is it possible to change the list view threshold in SharePoint Online?

You may wonder whether increasing the list view threshold is the right solution instead of focusing on workarounds. Unfortunately, SharePoint Online doesn't allow this limit to be changed. However, in on-premises environments, it can be adjusted using the SharePoint resource throttling settings.

4. What are the restrictions and limitations in the SharePoint document library?

Understanding the SharePoint Online document library limitations is essential to avoid performance issues and enhance the overall efficiency of file and folder management. Being aware of these boundaries helps prevent unexpected errors and ensures smoother collaboration throughout your organization.

  • Item limit: A single document library can store up to 30 million files and folders. However, managing the library performance becomes increasingly challenging as the total file and folder count increases to a certain limit.
  • List view threshold: SharePoint enforces a 5,000-item threshold for list views. This doesn't limit how many items you can store in a document library but restricts how many can be retrieved in a single view or query. Exceeding this limit may lead to performance issues or errors when displaying or querying large sets of items.
  • File size limit: In a SharePoint document library, the maximum file size you can upload is 250 GB per file. Although 250 GB files of this size are supported, they can impact overall performance within the document library. Additionally, large files may require more time for processes such as search indexing and version history updates.
  • Sync limitations: The OneDrive sync client can handle up to 300,000 items total across all synced libraries. Syncing more than this can result in errors or degraded performance, especially with deeply nested folders.
  • Unique permission limits: A SharePoint document library supports up to 50,000 uniquely permissioned files or folders. Once a library or folder exceeds 100,000 items, you cannot break permissions inheritance on the library, or folder.
  • URL character limit: Due to long file or folder names and deeply nested folders, you may exceed SharePoint Online's 400-character URL limit. To avoid these issues, use short names and limit folder nesting.
  • Folder sharing restrictions: SharePoint limits folder sharing to 50,000 items, which also includes items stored in subfolders. If this limit is exceeded, you can't share the folder. To overcome this, move some items to a different folder or share individual files.
  • File and folder name restrictions: In SharePoint Online, the following names are restricted for files and folders: .lock, CON, PRN, AUX, NUL, COM0–COM9, LPT0–LPT9, _vti_, desktop.ini. Additionally, file or folder names cannot begin with a space or with the characters ~$.

5. How to get the number of files and subfolders in a SharePoint document library using Power Automate?

SharePoint sites let you view the total item count in a document library or folder, but regularly monitoring it is key to avoiding issues with the 5,000-item list view threshold. Instead of checking manually, what if you could receive email alerts when a library or folder is nearing the limit? That would be a relief, right? That’s where Power Automate can help!

Count files and subfolders in a SharePoint document library using Power Automate

To automate the process of getting count of files and subfolders within a document library or any of its folder using Power Automate, follow the steps below:

  • Sign in to Power Automate, create a new scheduled cloud flow, give it a name, and set the desired frequency (e.g., daily or weekly).
  • Add the Send an HTTP request to SharePoint action with the following details: Site Address (Provide Site address), Uri:
    /_api/web/GetFolderByServerRelativeUrl('<FolderRelativePath>')/?$expand=Folders,Files
  • Click Show all under Advanced parameters, then in the Headers section, enter the key as Accept and the value as application/json;odata=verbose.
  • Add a Parse JSON action to process the SharePoint folder and file data. In the Content field, select the Body output from the HTTP request and provide the following JSON payload in the Schema field.
    {"d":{"Files":{"results":[]},"Folders":{"results":[]}}} 
  • Add a Condition action, then insert the following expression in the value field. Set the 'greater than or equal to' condition to your desired value (e.g., ≥ 4500).
    add(length(body('Parse_JSON')?['d']?['Files']?['results']),length(body('Parse_JSON')?['d']?['Folders']?['results'])) 
  • Under the true branch, add a Send an email (V2) action. Specify the desired "To" address, subject, and use the following body content (you can customize as needed):
    File count: @{length(body('Parse_JSON')?['d']?['Files']?['results'])} 
    Folder count: @{length(body('Parse_JSON')?['d']?['Folders']?['results'])} 
    Total items: @{add(length(body('Parse_JSON')?['d']?['Files']?['results']), 
    length(body('Parse_JSON')?['d']?['Folders']?['results']))} 
  • Finally, Save and Test the flow to get alerts for list view threshold limit in SharePoint.

For a clear visual representation of the flow, refer to the GIF image provided below.

automated-sharepoint-threshold-alert-power-automate

Kickstart Your Journey With
AdminDroid

Your Microsoft 365 Companion with Enormous Reporting Capabilities

Download Now
User Help Manuals Compliance Docs
x
Delivering Reports on Time
Want a desired Microsoft 365 reports every Monday morning? Ensure automated report distribution and timely delivery with AdminDroid's Scheduling to your email anytime you need.
Delivering Reports on Time
Schedule tailored reports to execute automatically at the time you set and deliver straight to the emails you choose. In addition, you can customize report columns and add inteligent filtering to the activities just from the previous day to suit your Microsoft 365 report requirements.
Set It, Schedule It, See Results- Your Reports, Your Way, On Your Time!
Time Saving
Automation
Customization
Intelligent Filtering
Give Just the Right Access to the Right People
Grant fine-tuned access to any Microsoft 365 user with AdminDroid’s Granular Delegation and meet your organization’s security and compliance requirements.
Give Just the Right Access to the Right People
Create custom roles loaded with just the right permissions and give access to admins or normal users within AdminDroid. The result? A streamlined Microsoft 365 management experience that aligns your organization's security protocols and saves your invaluable time and effort.
Align, Define, Simplify: AdminDroid's Granular Delegation
Smart Organizational Control
Effortless M365 Management
Simplified Access
Advanced Alerts at a Glance
Receive quick notifications for malicious Microsoft 365 activities. Engage with the AdminDroid’s real-time alert policies crafted to streamline your security investigations.
Advanced Alerts at a Glance
Stay informed of critical activities like suspicious emails and high-risk logins, bulk file sharing, etc. Through creating and validating ideal alert policies, AdminDroid provides a comprehensive approach to real-time monitoring and management of potential threats within your organization.
AdminDroid Keeps You Always Vigilant, Never Vulnerable!
Proactive Protection
Real-time Monitoring
Security Intelligence
Threat Detection
Merge the Required Data to One Place
Combine multiple required columns into one comprehensive report and prioritize the information that matters most to you with AdminDroid’s Advanced Column Customization.
Merge the Required Data to One Place
This column merging capability offers a flexible way to add different columns from various reports and collate all the essential data in one place. Want to revisit the customized report? Save it as a 'View’, and your unique report is ready whenever you need it.
Merge with Ease and Save as Views!
Custom Reporting
Unique View
Desired Columns
Easy Data Interpretation
Insightful Charts and Exclusive Dashboards
Get a quick and easy overview of your tenant's activity, identify potential problems, and take action to protect your data with AdminDroid’s Charts and Dashboards.
Insightful Charts and Exclusive Dashboards
With AdminDroid charts and dashboards, visualize your Microsoft 365 tenant in ways you've never thought possible. It's not just about viewing; it's about understanding, controlling, and transforming your Microsoft 365 environment.
Explore Your Microsoft 365 Tenant in a Whole New Way!
Executive overviews
Interactive insights
Decision-making
Data Visualization
Efficient Report Exporting for Microsoft 365
Downloading your reports in the right file format shouldn’t be a hassle with AdminDroid’s Report Export. Experience seamless report exporting in various formats that cater to your needs.
Efficient Report Exporting for Microsoft 365
Navigate through diverse options and export Microsoft 365 reports flawlessly in your desired file format. Tailor your reports precisely as you need them and save them directly to your computer.
Take Control, Customize and Deliver- Your Office 365 Data, Exported in Your Way!
Easy Export
Seamless Downloading
Data Control
Manage Microsoft 365

Get AdminDroid Office 365 Reporter Now!