I have this script to loop through all site collections >> and all document libraries >> then list the folders in this format "Site Name >> List Name >> Folder Name":

$AdminUrl = "https://*****-admin.sharepoint.com/"
Connect-PnPOnline -Url $AdminUrl -Interactive 
#sharepoint online get all site collections PowerShell
$SiteColl = Get-PnPTenantSite
#sharepoint online PowerShell iterate through all site collections
ForEach($Site in $SiteColl)
   Connect-PnPOnline -Url $Site.Url -Interactive
   $Webs = Get-PnPSubWeb -Recurse -IncludeRootWeb
    #Get All document libraries
ForEach($Web in $Webs)
               $DocumentLibraries = Get-PnPList -Web $Web | Where-Object {$_.BaseType -eq "DocumentLibrary" -and $_.Title -ne "Site Assets" -and $_.Hidden -eq $false}
    #Iterate through each document library
    ForEach($Library in $DocumentLibraries)
               $f =   Get-PnPFolder -List $Library
               ForEach($folder in $f)
               Write-Host $Site.Title " --> "  $Library.Title  " --> " $folder.Name

but the issue I am facing is that Get-PnPFolder -List $Library will get all the main folders and sub-folders. So how can I restrict this command to only get the main folders (first level folders) without sub-folders?

1 Answer 1


I don't think it is possible to get only the top-level folders using Get-PnPFolder command.

As per the source code, Get-PnPFolder uses CamlQuery.CreateAllFoldersQuery() to retrieve the folders inside the provided list/library.

And CamlQuery.CreateAllFoldersQuery() creates a query that can be used to recursively get all of the folders in a list/library.

Source: SP.CamlQuery.createAllFoldersQuery() Method


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.