Export Document Library File-Folder-SubFolder Structure to CSV

Requirement: Get the complete structure of all folders-subfolder-files from a SharePoint document library and export them to a CSV file.

PowerShell Script to Iterate through each folder and Sub-folder and get all files:

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue 

#Function to get all files of a folder
Function GetFiles-ByFolder([Microsoft.SharePoint.SPFolder]$Folder)
{
    write-host -f Yellow "Processing Folder:"$Folder.URL
    Foreach($File in $Folder.Files)
    {
        $Content = $Folder.Name + "," + $Folder.URL +"," + $File.Name
        #Append content to CSV file
        Add-content $OutPutFile $Content
        Write-host $Content
    }
    
    #Call the function for each subfolder - Excluding "Forms"
    $Folder.SubFolders | Where {$_.Name -ne "Forms" } | Foreach-Object {
    GetFiles-ByFolder $_
    }
}
 
#Variables
$SiteURL = "https://opera.crescent.com/sites/sales"
$ListName ="Shared Documents"
$OutPutFile = "C:\LibraryFiles.csv"

#Delete the CSV file if exists
If (Test-Path $OutPutFile) { Remove-Item $OutPutFile }

#Write CSV headers
Add-Content $OutPutFile "Folder Name, Relative URL, File Name"

#Get site and list objects
$Web = Get-SPWeb $SiteURL
$List = $Web.Lists[$ListName]
$Folder = $List.RootFolder

#Call the function for Root folder
GetFiles-ByFolder $Folder

This exports the inventory of all files and folders structure to a CSV file!.

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. Passionate about sharing the deep technical knowledge and experience to help others, through the real-world articles!

4 thoughts on “Export Document Library File-Folder-SubFolder Structure to CSV

Leave a Reply

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