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).
- # Input Parameters
- $siteURL="https://c986.sharepoint.com/sites/dev"
- $folder="/Shared Documents"
-
- # Loop through to get all the folders and subfolders
- Function GetFolders($folderUrl)
- {
- $folderColl=Get-PnPFolderItem -FolderSiteRelativeUrl $folderUrl -ItemType Folder
- # Loop through the folders
- foreach($folder in $folderColl)
- {
- $newFolderURL= $folderUrl+"/"+$folder.Name
- write-host -ForegroundColor Green $folder.Name " - " $newFolderURL
- # Call the function to get the folders inside folder
- GetFolders($newFolderURL)
- }
- }
-
- # Connect to SharePoint Online site
- Connect-PnPOnline –Url $siteURL –Credentials (Get-Credential)
-
- # Call the functions
- GetFolders($folder)
Note: Updated the script as per the comments. bug fix - removed the break command.
Open PowerShell window and run the following command.
folderlocation – GetFolders.ps1 file location
Run the following command,
Thus in this blog, you saw how to get all the folders and subfolders from SharePoint Online Document Library using PnP PowerShell.