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 to 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 is a SharePoint Architect with Two decades of SharePoint Experience. He loves sharing his knowledge and experiences with the SharePoint community, through his real-world articles!

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

Leave a Reply