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 I can restrict this command to only get the main folders (first level folders) without sub-folders?
Here is the updated script:
$AdminUrl = "https://***-admin.sharepoint.com/"
Connect-PnPOnline -Url $AdminUrl -Interactive
# SharePoint online get all site collections PowerShell
$SiteColl = Get-PnPTenantSite
$csvOutput = @()
# 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 " --> " $folder.ServerRelativeUrl
$csvOutput += [PsCustomObject]@{SiteTitle = $Site.Title; LibraryTitle = $Library.Title; Folder = $folder.Name; FolderPath = $folder.ServerRelativeUrl}
}
}
}
}
$csvOutput | Export-Csv -NoTypeInformation -Path "D:\export123.csv"
And the csvOutput will have values such as:
NewRoot --> dv --> test123 --> /dv/test123
NewRoot --> dv --> P100 --> /dv/P100
NewRoot --> dv --> WIP --> /dv/P100/WIP
NewRoot --> Site Pages --> Templates --> /SitePages/Templates
NewRoot --> tagggg --> a1 --> /tagggg/a1
NewRoot --> tagggg --> a2 --> /tagggg/a1/a2
NewRoot --> testdcdc --> test --> /testdcdc/test