#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 }