SharePoint Online: Site Documents Inventory (Library, Folder, Sub-Folder and Files) Report using PowerShell

Requirement: Generate an Inventory report that contains all document Libraries, Folders, Sub-Folders, and File detail from a SharePoint Online site collection.

SharePoint Online: Site Inventory Report using PowerShell

Do you need to create an inventory report of all the documents in a SharePoint Online site? Well, You can use PowerShell to do that! In this blog post, I’ll show you how to create an inventory report of all the documents on a site using PowerShell script. As well as information about each document such as file name, file type, last modified date, etc.

We wanted to find the number of files, folders, and sub-folders in each document library in a SharePoint Online site. This PowerShell script extracts the inventory of all document libraries, folders, sub-folders, and files from a given SharePoint Online site collection to a CSV report.

#Function to collect site Inventory
Function Get-PnPSiteInventory
{
[cmdletbinding()]
   param([parameter(Mandatory = $true, ValueFromPipeline = $true)] $Web)

    #Skip Apps
    If($Web.url -notlike "$SiteURL*") { return }
   
    Write-host "Getting Site Inventory from Site '$($Web.URL)'" -f Yellow
 
    #Exclude certain libraries
    $ExcludedLists = @("Form Templates", "Preservation Hold Library") 
                               
    #Get All Document Libraries from the Web
    $Lists= Get-PnPProperty -ClientObject $Web -Property Lists
    $Lists | Where-Object {$_.BaseType -eq "DocumentLibrary" -and $_.Hidden -eq $false -and $_.Title -notin $ExcludedLists -and $_.ItemCount -gt 0} -PipelineVariable List | ForEach-Object {
        #Get Items from List   
        $global:counter = 0;
        $ListItems = Get-PnPListItem -List $_ -PageSize $Pagesize -Fields Author, Created -ScriptBlock `
                 { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete ($global:Counter / ($_.ItemCount) * 100) -Activity "Getting Inventory from '$($_.Title)'" -Status "Processing Items $global:Counter to $($_.ItemCount)";}
        Write-Progress -Activity "Completed Retrieving Inventory from Library $($List.Title)" -Completed
     
            #Get Root folder of the List
            $Folder = Get-PnPProperty -ClientObject $_ -Property RootFolder
            
            $SiteInventory = @()
            #Iterate through each Item and collect data           
            ForEach($ListItem in $ListItems)
            {  
                #Collect item data
                $SiteInventory += New-Object PSObject -Property ([ordered]@{
                    SiteName  = $Web.Title
                    SiteURL  = $Web.URL
                    LibraryName = $List.Title
                    ParentFolderURL = $Folder.ServerRelativeURL
                    Name = $ListItem.FieldValues.FileLeafRef
                    Type = $ListItem.FileSystemObjectType
                    ItemRelativeURL = $ListItem.FieldValues.FileRef
                    CreatedBy = $ListItem.FieldValues.Author.Email
                    CreatedAt = $ListItem.FieldValues.Created
                    ModifiedBy = $ListItem.FieldValues.Editor.Email
                    ModifiedAt = $ListItem.FieldValues.Modified
                })
            }
            #Export the result to CSV file
            $SiteInventory | Export-CSV $CSVReport -NoTypeInformation -Append
        }
}

#Parameters
$SiteURL = "https://crescent.SharePoint.com/sites/Marketing"
$CSVReport = "C:\Temp\SiteInventory.csv"
$Pagesize = 2000

#Connect to Site collection
Connect-PnPOnline -Url $SiteURL -Interactive

#Delete the Output Report, if exists
If (Test-Path $CSVReport) { Remove-Item $CSVReport }    
  
#Call the Function for all Webs
Get-PnPSubWeb -Recurse -IncludeRootWeb | ForEach-Object { Get-PnPSiteInventory $_ }
   
Write-host "Site Inventory Report has been Exported to '$CSVReport'"  -f Green

Once executed, this script generates a CSV file in this format:

sharepoint online site inventory report using powershell

If you need to generate a documents inventory report for a one-single document library, use this script: SharePoint Online: PowerShell to List All Files Inventory in a Document Library

In conclusion, creating a document inventory in SharePoint can be a time-consuming task, especially when you have multiple document libraries and thousands of documents. However, using PowerShell, you can automate the process and generate a document inventory quickly and efficiently. By using the script provided in this tutorial, you can quickly and easily generate a document inventory that contains important information such as the title, URL, library title, author, and created date of each document to a CSV file. This inventory can be used for various purposes, such as auditing, compliance, and reporting.

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!

23 thoughts on “SharePoint Online: Site Documents Inventory (Library, Folder, Sub-Folder and Files) Report using PowerShell

  • Can we customize it to generate report only for restricted folders

    Reply
  • Great script! it worked well. Can you tell me how to add the File Size to the script?
    Thanks!

    Reply
    • Use:
      $ListItem.FieldValues.File_x0020_Size or $ListItem.FieldValues.SMTotalSize.LookupId

      Reply
  • Hi there – thanks for this script. Looks great and just what I need.
    On the off chance this is seen I’m having some difficulties running this script. There are no errors whilst running it, it just hangs after being prompted to enter credentials after MFA. Checking task manager the PowerShell process doesn’t really move much and the file output is never created
    Running PS version 5.1
    Many thanks

    Reply
  • Hi Salaudeen,

    Great script and really helpful, I have a scenario where I couldn’t run PNP PowerShell as its not activated at the tenant level. Can it be done using CSOM? Thanks

    NK

    Reply
  • I need help to resolve this error that I am getting. I have changed the “$web” values to “$subweb” and I am still getting the error.

    Get-PnPProperty: Cannot bind parameter ‘ClientObject’.
    Cannot convert the “Microsoft.SharePoint.Client.Web” value of type “Deserialized.Microsoft.SharePoint.Client.Web” to type “Microsoft.SharePoint.Client.ClientObject”

    Reply
    • Solved.
      I have just tested the code and it works very well with PowerShell 5.1.
      My issue is with PowerShell 7.2.6, which I am think could be a bug.

      Reply
  • Great script. Is there a way to add a field to the CSV. Just to display the folder where the files is saved. rather than the whole path

    $SiteInventory += New-Object PSObject -Property ([ordered]@{
    SiteName = $Web.Title
    SiteURL = $Web.URL
    LibraryName = $List.Title
    ParentFolderURL = $Folder.ServerRelativeURL
    Name = $ListItem.FieldValues.FileLeafRef
    Type = $ListItem.FileSystemObjectType
    ItemRelativeURL = $ListItem.FieldValues.FileRef
    CreatedBy = $ListItem.FieldValues.Author.Email
    CreatedAt = $ListItem.FieldValues.Created
    ModifiedBy = $ListItem.FieldValues.Editor.Email
    ModifiedAt = $ListItem.FieldValues.Modified
    })

    Need to add “Folder name” here to display where the file is loacated . Currently displayes the serverUrl which is confusing for end users to read

    Reply
  • Hello and thanks for this script!

    How do you run the report on a specific document library? For example, I want to run this script against a document library called “Shared With Guests”. I wasn’t quite sure where I can add that in.

    Thanks!
    Ryan

    Reply
  • Sorry, Connect-PnPOnline shows
    You are running the legacy version of PnP PowerShell.

    This version will be archived soon which means that while staying available, no updates or fixes will be released.
    Consider installing the newer prereleased cross-platform version of PnP PowerShell.
    This version has numerous improvements and many more cmdlets available.

    Maybe we have to update the code… Thanks a lot!

    Reply
    • You can update to the new PnP PowerShell module with: Install-Module -Name “PnP.PowerShell”, However all the script in this article will work without any modification both in legacy version of PnP PowerShell and with the new module.

      Reply
      • Good to know. Thanks!

        Reply
  • Thanks for your excellent and helpful site!

    When I run this script, I get the following errors:
    ======================================================

    WARNING: Parameter ‘Web’ is obsolete. The -Web parameter will be removed in a future release. Use Connect-PnPOnline -Url [subweburl] instead to connect to a subweb.
    Get-PnPListItem : Missing an argument for parameter ‘ScriptBlock’. Specify a parameter of type ‘System.Management.Automation.ScriptBlock’ and try again.
    At line:23 char:101
    + … -Web $web -PageSize $Pagesize -Fields Author, Created -ScriptBlock `
    + ~~~~~~~~~~~~
    + CategoryInfo : InvalidArgument: (:) [Get-PnPListItem], ParameterBindingException
    + FullyQualifiedErrorId : MissingArgument,PnP.PowerShell.Commands.Lists.GetListItem

    Reply
  • This comment has been removed by the author.

    Reply
  • This is fantastic, what is the syntax to add CONTENT TYPE as an additional field to export? Thank you for this and an excellent site

    Reply
  • Too bad this is not listing the file size + number of versions 🙂

    Reply
  • Love this… needed to find files modified for a SharePoint Online document library in the last week, and this script is ideal. The site inventory is beautifully presented in Excel, ideal for sorting & filtering etc. Thanks a million ��

    Reply
  • Can I skip folders from this report? I just need files inventory. Please help

    Reply
    • Sure, Just add a where condition to Filter: $ListItems | Where {$_.FileSystemObjectType -eq “File”}

      Reply

Leave a Reply

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