Find empty folders in a SharePoint site using PowerShell PnP
We still have this debate about Folders vs. Metadata. Which one is better? Should I continue to use folders? etc…
It’s OK to use a bit of both if you want. There are pros and cons for each one, and really depends on your organization requirements, user experience, and so on.
Today, we’re not talking about choosing one or the other, but rather assuming you’ve got folders, and you want to clean up the empty ones!
By now, readers know one of my favourite topic is SharePoint PowerShell PnP 😅 So let’s get started!
The script
The script itself is straight forward, but let’s go quickly through the stages.
Step 1, we connect to our target site as usual,
Step 2, we loop through each document library in a site where the folder size should be 0 (zero),
Step 3, we export the results
#Connect to SPO Connect-PnPOnline -Url https://<YOUR_TENANT_NAME>.sharepoint.com/sites/<YOUR_SITE> #Store in variable all the document libraries in the site $DocLibrary = Get-PnPList | Where-Object { $_.BaseTemplate -eq 101 } $LogFile = "C:\users\$env:USERNAME\Desktop\SPOEmptyFolders.csv" $results = @() foreach ($DocLib in $DocLibrary) { #Get list of all folders in the document library $AllItems = Get-PnPListItem -PageSize 1000 -List $DocLib -Fields "SMTotalFileStreamSize", "Author" #Loop through each files/folders in the document library for folder size = 0 foreach ($Item in $AllItems) { if ((([uint64]$Item["SMTotalFileStreamSize"]) -eq 0)) { Write-Host "Empty folder:" $Item["FileLeafRef"] -ForegroundColor Yellow #Creating object to export in .csv file $results += [pscustomobject][ordered] @{ CreatedDate = [DateTime]$Item["Created_x0020_Date"] FileName = $Item["FileLeafRef"] CreatedBy = $Item.FieldValues.Author.LookupValue FilePath = $Item["FileRef"] SizeInMB = ($Item["SMTotalFileStreamSize"] / 1MB).ToString("N") LastModifiedBy = $Item.FieldValues.Editor.LookupValue EditorEmail = $Item.FieldValues.Editor.Email LastModifiedDate = [DateTime]$Item["Modified"] } }#end of IF statement } } $results | Export-Csv -Path $LogFile -NoTypeInformation
Notes:
- Use the
-PageSize <your_number>
to batch the loop in case you have a lot of items (optional) - The
SizeInMB = ($Item["SMTotalFileStreamSize"] / 1MB).ToString("N")
is totally unnecessary but just for confirmation the folder is empty - Choose as many properties as you wish to export according to your requirements
The results
Once we run the script, you’ll have an overview of the empty folders, and a .csv file will be exported to your desktop.
And voilà!