SharePoint Online: Get All Folders from List or Library using PowerShell

Requirement: Get All Folders from a SharePoint Online list using PowerShell.

PowerShell to Get All Folders in a SharePoint Online List

PowerShell to Get All Folders in a SharePoint Online List

In many cases, you may need to get a list of all folders within a SharePoint Online list or library. This can be accomplished using PowerShell. This blog post will show you how to get all folders from a list or library using PowerShell!

Here is the CAML-based approach to get all folders and sub-folders recursively from a list:

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Set Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Documents"

#Get Credentials to connect
$Cred = Get-Credential
 
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

    #Get the List
    $List = $Ctx.web.Lists.GetByTitle($ListName)
    
    #Define CAML Query to get all folders from list recursively
    $CAMLQuery = New-Object Microsoft.SharePoint.Client.CamlQuery
    $CAMLQuery.ViewXml = "<View Scope='RecursiveAll'><Query><Where><Eq><FieldRef Name='FSObjType'/><Value Type='Integer'>1</Value></Eq></Where></Query></View>"

    #Get All Folders from the List
    $Folders = $List.GetItems($CAMLQuery)
    $Ctx.Load($Folders)
    $Ctx.ExecuteQuery()

    #Iterate through Each Folder
    ForEach($Folder in $Folders)
    {
        #Get the Folder's Server Relative URL
        Write-host $Folder.FieldValues['FileRef']
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

This PowerShell gets the list of folders from a SharePoint Online library.

SharePoint Online: Get Sub-Folders from a SharePoint Online List using PowerShell

Let’s get all top-level folders from a list or library in SharePoint Online.

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Set Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Documents"

#Get Credentials to connect
$Cred = Get-Credential
 
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

    #Get the List
    $List = $Ctx.web.Lists.GetByTitle($ListName)

    #Get Sub-Folders of the List
    $SubFolders = $List.RootFolder.Folders
    $Ctx.Load($SubFolders)
    $Ctx.ExecuteQuery()
    
    #Iterate through Each SubFolder
    ForEach($Folder in $SubFolders)
    {
        #Get the Folder's Server Relative URL
        Write-host $Folder.Name
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Similarly, If you want to get all subfolders of a specific folder, use:

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Set Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$FolderRelativeURL = "/sites/marketing/Shared Documents/2018"

#Get Credentials to connect
$Cred = Get-Credential
 
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

    #Get Sub-Folders of a Folder
    $SubFolders = $Ctx.web.GetFolderByServerRelativeUrl($FolderRelativeURL).Folders
    $Ctx.Load($SubFolders)
    $Ctx.ExecuteQuery()
    
    #Iterate through Each SubFolder
    ForEach($Folder in $SubFolders)
    {
        #Get the Folder's Server Relative URL
        Write-host $Folder.Name
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

SharePoint Online: Get All Folders Recursively from a SharePoint Online List using PowerShell

Here is the PowerShell script to recursively get all folders from a SharePoint Online List or library.

#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

#Function to Get Sub-folders of a Folder in SharePoint Online
Function Get-SPOFolders([Microsoft.SharePoint.Client.Folder]$Folder)
{
    Try {         
        Write-host $Folder.ServerRelativeUrl
 
        #Process all Sub Folders
        $Ctx.Load($Folder.Folders)
        $Ctx.ExecuteQuery()
 
        #Iterate through each sub-folder of the folder
        Foreach ($Folder in $Folder.Folders)
        {
            #Call the function recursively
            Get-SPOFolders $Folder
        }
    }
    Catch {
        write-host -f Red "Error Getting Folder!" $_.Exception.Message
    }
}

#Set Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Documents"

#Get Credentials to connect
$Cred = Get-Credential
 
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

    #Get the Root Folder of a List
    $List = $Ctx.Web.Lists.GetByTitle($ListName)
    $RootFolder = $List.RootFolder
    $Ctx.Load($RootFolder)
    $Ctx.ExecuteQuery()
    
    #Call the Function to get all folders recursively from the list
    Get-SPOFolders $RootFolder
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

PnP PowerShell to Get All Folders from a SharePoint Online Document Library

Here is how to get all folders (and subfolders) recursively from a SharePoint Online list or library:

#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$ListName = "Branding"
  
Try {
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Interactive
  
    #Get All Folders from the document Library
    $Folders = Get-PnPFolder -List $ListName
     
    Write-host "Total Number of Items in the Folder in the list:" $Folders.Count

    #Get Folder/Subfolder details
    $Folders | Select Name, TimeCreated, ItemCount, ServerRelativeUrl
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}

Let’s get all folders from a given document library and export them to a CSV file using PnP PowerShell.

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/legal"
$ListName = "Work"
$CSVPath = "C:\Temp\Folders.csv"
$FoldersInventory = @()

#Connect to Site
Connect-PnPOnline -Url $SiteURL -Interactive

#Get the List
$List =  Get-PnPList -Identity $ListName

#Get all Folders from List - with progress bar
$global:counter = 0;
$Folders = Get-PnPListItem -List $List -PageSize 500 -Fields FileLeafRef -ScriptBlock { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete ($global:Counter / ($List.ItemCount) * 100) -Activity "Getting Folders from List:" -Status "Processing Items $global:Counter to $($List.ItemCount)";}  | Where {$_.FileSystemObjectType -eq "Folder"}
  
#Iterate through all folders in the list
$Folders | ForEach-Object {
    #Collect Folder data
    $FoldersInventory += [PSCustomObject] @{
        FolderName = $_.FieldValues.FileLeafRef
        URL = $_.FieldValues.FileRef
    }   
}
$FoldersInventory
$FoldersInventory | Export-Csv -Path $CSVPath -NoTypeInformation

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

Leave a Reply

Your email address will not be published. Required fields are marked *