Contents

Find empty folders in SharePoint using PowerShell

Contents

 

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 PnP PowerShell 😅

So let’s get started!
 

Script

The script itself is straight forward, but let’s go quickly through the stages.

  1. We connect to our target site as usual,
  2. We loop through each document library in a site where the folder size should be 0 (zero),
  3. We export the results
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
#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 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

 

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.

/images/powershell-screenshots/find-empty-folders-in-spo.jpeg