Tutorial
SharePoint large files and empty folders: PowerShell script
A PnP PowerShell script that lists large SharePoint files, versions included, and empty folders across several sites, then removes the empty ones on request.
A SharePoint site that keeps growing for no obvious reason almost always hides two things: a few large files, often videos or exports whose versions weigh several times the file itself, and dozens of empty folders left behind by a folder structure created up front. Hunting for them in the interface, library by library, does not scale to twenty sites. Here is a PnP PowerShell script that inventories both across several sites at once, with sizes including versions, and removes the empty folders only when you tell it to.
Why look for large files and empty folders?
SharePoint storage is a quota shared by the whole tenant: 1 TB plus 10 GB per license. Every version of a file counts against it. A 300 MB video edited ten times can use 3 GB, while File Explorer only shows 300 MB. That is why a library's displayed size and the space it actually consumes so often differ: as Microsoft Learn points out, storage reports include versions.
Empty folders take no space. But they clutter navigation, skew folder-based browsing and leave users wondering where a file belongs. In a library organized around a file plan, they also show which branches nobody uses.
Before the script: the no-code tools
For a single site, the built-in tools are enough:
| Storage Metrics | The script | |
|---|---|---|
| Where | Site settings > Storage Metrics | PowerShell 7 on your machine |
| Scope | One site, folder by folder | Several sites, every library |
| Version size | Yes, for folders and files | Yes, a dedicated column per file |
| Empty folders | No | Yes, even nested ones |
| Export | No | Two CSV files |
| Removal | No | Empty folders, to the recycle bin, on request |
If you manage a single site, start with Storage Metrics: it is enough to find the heaviest folder. The script pays off when you need a report across several sites, to share or to rerun every quarter.
Prerequisites
They are the same as for the other scripts in the series, detailed in the article on bulk-restoring the SharePoint recycle bin:
- PowerShell 7.4 or later (
winget install --id Microsoft.PowerShell --source winget), started withpwsh; - the PnP.PowerShell module (
Install-Module PnP.PowerShell -Scope CurrentUser); - your own Entra ID application for PnP PowerShell, mandatory since September 2024: its application (client) ID is the script's
ClientId; - permissions: member of the Owners group or admin of every site you scan. To remove folders, you need at least edit rights on the libraries involved.
What the script does
- It connects to each site in the list, with a Microsoft sign-in window (MFA included).
- It goes through the document libraries, skipping system libraries (Site Assets, Style Library, Form Templates), or only the ones you name with
-Library. - It lists files above the threshold, 100 MB by default, with two sizes: the current version and the total including versions.
- It finds empty folders, meaning folders with no file at all, even deep in their subfolders.
- It exports two CSV files to your Documents folder. Without
-RemoveEmptyFolders, it stops there: nothing is changed. - With
-RemoveEmptyFolders, it sends the empty folders to the site recycle bin, deepest first, after checking again that each one is still empty.
To decide whether a folder is empty, the script does not compare every folder with every file, which gets very slow beyond a few thousand items. It walks up the tree from each file once and records every folder it passes through. Folders never recorded are empty. A 50,000-item library is handled in a single read.
I tested it with PowerShell 7.6 and PnP.PowerShell 3.4.1 on the demo tenant: a three-level tree of empty folders, an empty subfolder inside a full folder, and a 3 MB video uploaded three times to create versions.
The full script
Copy it into a Get-SPStorageCleanupReport-en.ps1 file, or download it directly.
#Requires -Version 7.4
#Requires -Modules PnP.PowerShell
<#
.SYNOPSIS
Finds large files and empty folders in the document libraries of one or
more SharePoint Online sites, and can remove the empty folders.
.DESCRIPTION
For each site, the script:
1. connects with PnP.PowerShell;
2. goes through the document libraries (system libraries excluded);
3. lists files above the threshold, with their size and the space
taken by their versions;
4. lists folders that contain no file, at any level;
5. exports two CSV reports.
Only with -RemoveEmptyFolders does it then send the empty folders to the
site recycle bin, deepest first, after checking again that each one is
still empty. Without that switch, it changes nothing.
.PARAMETER SiteUrl
One or more site URLs, for example https://contoso.sharepoint.com/sites/Finance
.PARAMETER ClientId
ID of the Entra ID application used by PnP.PowerShell (see the prerequisites).
.PARAMETER Library
Optional. Title of one or more libraries to scan. Default: all of them.
.PARAMETER MinSizeMB
Large file threshold, in MB. 100 by default.
.PARAMETER RemoveEmptyFolders
Sends the empty folders to the recycle bin. Without this switch, the script only lists them.
.PARAMETER ReportFolder
Folder for the CSV reports. Default: your Documents folder.
.EXAMPLE
# 1) Report only, on two sites
.\Get-SPStorageCleanupReport-en.ps1 `
-SiteUrl "https://contoso.sharepoint.com/sites/Finance", "https://contoso.sharepoint.com/sites/HR" `
-ClientId "00000000-0000-0000-0000-000000000000"
.EXAMPLE
# 2) Remove the empty folders, once the report has been checked
.\Get-SPStorageCleanupReport-en.ps1 -SiteUrl "https://contoso.sharepoint.com/sites/Finance" `
-ClientId "00000000-0000-0000-0000-000000000000" -Library "Documents" -RemoveEmptyFolders
#>
[CmdletBinding()]
param(
[Parameter(Mandatory)] [string[]] $SiteUrl,
[Parameter(Mandatory)] [string] $ClientId,
[string[]] $Library,
[ValidateRange(0, 250000)] [double] $MinSizeMB = 100,
[switch] $RemoveEmptyFolders,
[string] $ReportFolder = (Join-Path $HOME "Documents")
)
# Stop at the first unhandled error instead of carrying on blindly.
$ErrorActionPreference = "Stop"
$stamp = Get-Date -Format "yyyyMMdd-HHmmss"
$largeFiles = [System.Collections.Generic.List[object]]::new()
$emptyFolders = [System.Collections.Generic.List[object]]::new()
foreach ($site in $SiteUrl) {
# ----------------------------------------------------------------------
# 1. Connect to the site
# ----------------------------------------------------------------------
# -Interactive opens a Microsoft sign-in window (MFA included).
Write-Host "`nConnecting to $site ..." -ForegroundColor Cyan
Connect-PnPOnline -Url $site -Interactive -ClientId $ClientId
# ----------------------------------------------------------------------
# 2. Libraries to scan
# ----------------------------------------------------------------------
# Template 101 = document library. IsSystemList excludes "Site Assets",
# "Style Library" or "Form Templates" whatever the site language
# (never filter on the title).
$libraries = Get-PnPList -Includes BaseTemplate, IsSystemList, RootFolder | Where-Object {
$_.BaseTemplate -eq 101 -and -not $_.Hidden -and -not $_.IsSystemList -and
(-not $Library -or $_.Title -in $Library)
}
foreach ($lib in $libraries) {
Write-Host (" Library: {0}" -f $lib.Title)
# Load only the columns we need. -PageSize reads 2,000 items per page,
# which also gets past the 5,000-item list view threshold.
$items = @(Get-PnPListItem -List $lib -PageSize 2000 -Fields `
"FileRef", "FileDirRef", "FileLeafRef", "FSObjType",
"SMTotalFileStreamSize", "SMTotalSize", "_UIVersionString", "Modified", "Editor")
$files = @($items | Where-Object { $_["FSObjType"] -eq 0 })
$folders = @($items | Where-Object { $_["FSObjType"] -eq 1 })
# ------------------------------------------------------------------
# 3. Large files
# ------------------------------------------------------------------
# SMTotalFileStreamSize: size of the current version.
# SMTotalSize: total size, versions and metadata included.
foreach ($f in $files) {
$sizeMB = $f["SMTotalFileStreamSize"] / 1MB
if ($sizeMB -lt $MinSizeMB) { continue }
$totalMB = if ($f["SMTotalSize"]) { $f["SMTotalSize"].LookupId / 1MB } else { $sizeMB }
$largeFiles.Add([PSCustomObject][ordered]@{
Site = $site
Library = $lib.Title
File = $f["FileLeafRef"]
Path = $f["FileRef"]
SizeMB = [math]::Round($sizeMB, 1)
SizeWithVersionsMB = [math]::Round($totalMB, 1)
Version = $f["_UIVersionString"]
Modified = $f["Modified"].ToLocalTime()
ModifiedBy = $f["Editor"].Email
})
}
# ------------------------------------------------------------------
# 4. Empty folders
# ------------------------------------------------------------------
# A folder is empty when it holds no file, not even in its subfolders.
# We walk up the tree from each file once and record every folder we
# pass through: the folders never recorded are empty.
$root = $lib.RootFolder.ServerRelativeUrl
$withFiles = [System.Collections.Generic.HashSet[string]]::new([StringComparer]::OrdinalIgnoreCase)
foreach ($f in $files) {
$dir = $f["FileDirRef"]
while ($dir.Length -gt $root.Length -and $withFiles.Add($dir)) {
$dir = $dir.Substring(0, $dir.LastIndexOf("/"))
}
}
foreach ($d in $folders) {
if ($withFiles.Contains($d["FileRef"])) { continue }
$emptyFolders.Add([PSCustomObject][ordered]@{
Site = $site
Library = $lib.Title
Folder = $d["FileLeafRef"]
Path = $d["FileRef"]
Depth = ($d["FileRef"].Substring($root.Length) -split "/").Count - 1
Modified = $d["Modified"].ToLocalTime()
Status = "Empty"
})
}
}
# ----------------------------------------------------------------------
# 5. Remove the empty folders (only with -RemoveEmptyFolders)
# ----------------------------------------------------------------------
if ($RemoveEmptyFolders) {
# Deepest first: a parent folder is only removed after its subfolders.
$webUrl = (Get-PnPWeb).ServerRelativeUrl.TrimEnd("/")
$toRemove = $emptyFolders | Where-Object Site -eq $site | Sort-Object Depth -Descending
foreach ($e in $toRemove) {
try {
# Site-relative path, expected by the two commands below.
$siteRelative = $e.Path.Substring($webUrl.Length + 1)
# Check again right before acting: someone may have dropped a
# file since the scan. Files in subfolders count too.
$filesInside = @(Get-PnPFolderItem -FolderSiteRelativeUrl $siteRelative -ItemType File -Recursive)
if ($filesInside.Count -gt 0) { $e.Status = "Skipped: no longer empty"; continue }
# -Recycle sends the folder to the site recycle bin (93 days) instead of destroying it.
$parent = $siteRelative.Substring(0, $siteRelative.LastIndexOf("/"))
Remove-PnPFolder -Name $e.Folder -Folder $parent -Recycle -Force | Out-Null
$e.Status = "Sent to recycle bin"
}
catch {
# A folder locked by a retention label, a permission issue...:
# record it and move on.
$e.Status = "Failed: $($_.Exception.Message)"
}
}
}
Disconnect-PnPOnline
}
# --------------------------------------------------------------------------
# 6. Reports
# --------------------------------------------------------------------------
if (-not (Test-Path $ReportFolder)) { New-Item -ItemType Directory -Path $ReportFolder | Out-Null }
$largePath = Join-Path $ReportFolder "Large-files-$stamp.csv"
$emptyPath = Join-Path $ReportFolder "Empty-folders-$stamp.csv"
$largeFiles | Sort-Object SizeWithVersionsMB -Descending |
Export-Csv -Path $largePath -Encoding UTF8
$emptyFolders | Sort-Object Site, Path |
Export-Csv -Path $emptyPath -Encoding UTF8
$totalGB = ($largeFiles | Measure-Object SizeWithVersionsMB -Sum).Sum / 1KB
Write-Host ("`n{0} file(s) of {1} MB or more, {2:N1} GB including versions: {3}" -f $largeFiles.Count, $MinSizeMB, $totalGB, $largePath) -ForegroundColor Green
Write-Host ("{0} empty folder(s): {1}" -f $emptyFolders.Count, $emptyPath) -ForegroundColor Green
if (-not $RemoveEmptyFolders -and $emptyFolders.Count -gt 0) {
Write-Host "Nothing was removed. Check the CSV, then run again with -RemoveEmptyFolders." -ForegroundColor Yellow
}
Run it in two steps
First the report. It changes nothing, and takes several sites separated by commas:
.\Get-SPStorageCleanupReport-en.ps1 `
-SiteUrl "https://contoso.sharepoint.com/sites/Finance", "https://contoso.sharepoint.com/sites/HR" `
-ClientId "00000000-0000-0000-0000-000000000000"
You get two files in Documents. Here is what the large files report showed on the test set, run with -MinSizeMB 1:
| File | SizeMB | SizeWithVersionsMB | Version |
|---|---|---|---|
| Video-formation.mp4 | 3 | 9 | 3.0 |
Three 3 MB versions, 9 MB consumed: exactly the gap storage reports reveal at scale. Sort the CSV on SizeWithVersionsMB: the files at the top are where a version limit pays off most.
Then the empty folder cleanup, on the libraries you have checked:
.\Get-SPStorageCleanupReport-en.ps1 `
-SiteUrl "https://contoso.sharepoint.com/sites/Finance" `
-ClientId "00000000-0000-0000-0000-000000000000" `
-Library "Documents" `
-RemoveEmptyFolders
The Status column of the folders CSV then shows, for each one, "Sent to recycle bin", "Skipped: no longer empty" or the error message. On the test set, all five empty folders went to the recycle bin, and a second run found none left.
Pitfalls to know about
- Not every empty folder should go. On the demo tenant, the report also found the
PlansandSkillsfolders of the Agent Assets library, created by SharePoint for agents, and, in Documents, folders such as "General", typical of a library connected to Teams. Removing them can break a feature or simply bring the folder back. That is why the cleanup runs with-Library, one library at a time, after reading the report. - A folder holding only empty folders is empty. The script treats it as such and removes the subfolders first, then the parent. If you want to keep a file plan structure, do not run the removal on that library.
- Removing frees almost nothing. An empty folder weighs nothing, and an item sent to the recycle bin still counts against the quota for 93 days. To reclaim space, act on the large files and their versions.
- Versions are managed elsewhere. The script deletes no versions. To cut their weight, use version history limits at library, site or organization level. Note that changing the organization limit does not update existing libraries, and items under a retention policy keep their versions.
- Retention labels. A folder or item locked by a label cannot be removed: the CSV shows it as failed, which is expected.
- The scan only reads what you can see. Run with an account that cannot access every folder, the script would treat folders as empty when it simply cannot see their files. The check before removal has the same limit: run it with a site owner or admin account.
What I recommend
- Run the report on your heaviest sites, found in the SharePoint admin center (Storage used column of the active sites list).
- Compare the two sizes in the large files CSV: when the total is several times the file size, set a version limit on that library.
- Send the empty folder list to the site owner before removing anything: they know which folders belong to a file plan.
- Remove library by library, with
-Library, never across a whole site at once. - Schedule the report every quarter and keep the CSV files: how a site evolves matters more than a single snapshot.
Automation with PnP PowerShell is part of the training I run for administrators, Run SharePoint at tenant scale. And if you want to clean up a tenant that grew too fast, that is the kind of project I support as a consultant.
- SharePoint
- PowerShell
- PnP PowerShell
- Storage
- Administration
Sources
- Microsoft Learn — SharePoint storage management
- Microsoft Learn — Version history limits for document library and OneDrive overview
- Microsoft Learn — Plan version storage for document libraries
- PnP PowerShell — Get-PnPListItem
- PnP PowerShell — Remove-PnPFolder
- PnP PowerShell — Register your own Entra ID application
Share this article
Know a colleague or client who deals with this? Send them the article in one click.
Read next
Comments
Loading comments…