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.     # Loop through the folders  
  10.     foreach($folder in $folderColl)  
  11.     {                      
  12.        $newFolderURL= $folderUrl+"/"+$folder.Name   
  13.        write-host -ForegroundColor Green $folder.Name " - " $newFolderURL  
  14.        # Call the function to get the folders inside folder  
  15.        GetFolders($newFolderURL)  
  16.     }           
  17. }  
  18.   
  19. Connect to SharePoint Online site  
  20. Connect-PnPOnline –Url $siteURL –Credentials (Get-Credential)  
  21.   
  22. # Call the functions  
  23. GetFolders($folder)  

Note: Updated the script as per the comments. bug fix - removed the break command. 

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.