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

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