How To Get All The Folders And Subfolders From SharePoint Online Document Library Using PnP PowerShell

I have a document library named “Shared Documents” which has the following folder structure.

  • /Shared Documents
  • /Shared Documents/Articles
  • /Shared Documents/Articles/Screenshots
  • /Shared Documents/Scripts

You can download setup files from the releases section of the PnP PowerShell repository.

Copy the below script and paste it in a notepad. Save the file as GetFolders.ps1. This script will loop through all the folders inside “Shared Documents” and folders inside the folder (subfolders).

  1. # Input Parameters  
  2. $siteURL="https://c986.sharepoint.com/sites/dev"  
  3. $folder="/Shared Documents"  
  4.   
  5. # Loop through to get all the folders and subfolders  
  6. Function GetFolders($folderUrl)  
  7. {      
  8.     $folderColl=Get-PnPFolderItem -FolderSiteRelativeUrl $folderUrl -ItemType Folder  
  9.       
  10.     if($folderColl.Count -eq 0)  
  11.     {  
  12.        break;  
  13.     }  
  14.     else  
  15.     {  
  16.         # Loop through the folders  
  17.         foreach($folder in $folderColl)  
  18.         {                      
  19.           $newFolderURL= $folderUrl+"/"+$folder.Name   
  20.           write-host -ForegroundColor Green $folder.Name " - " $newFolderURL  
  21.   
  22.           # Call the function to get the folders inside folder  
  23.           GetFolders($newFolderURL)  
  24.         }          
  25.     }  
  26. }  
  27.   
  28. Connect to SharePoint Online site  
  29. Connect-PnPOnline –Url $siteURL –Credentials (Get-Credential)  
  30.   
  31. # Call the functions  
  32. GetFolders($folder)  

Open PowerShell window and run the following command.

  1. >cd "<folderlocation>"  

folderlocation – GetFolders.ps1 file location

Run the following command,

  1. >.\GetFolders.ps1  

 

Reference - Get-PnPFolderItem

Thus in this blog, you saw how to get all the folders and subfolders from SharePoint Online Document Library using PnP PowerShell.