SharePoint Storage Full Because of Version History

Microsoft SharePoint logo

Short answer: when SharePoint says your storage is full, the usual cause is old file versions. Every save keeps a copy, up to 500 per file by default, and those copies count against your organisation’s storage limit. Measure where the space has gone, check for retention policies and backups, trim old versions with a background job, empty the recycle bins, then turn on Microsoft’s automatic version history limits so it doesn’t build up again. The scripts we use are at the end of this article.

An engineering firm called us when OneDrive started showing red crosses on several PCs and their main projects library stopped syncing, with dozens of sync errors. Their Microsoft 365 organisation was at about 110% of its SharePoint storage limit, so SharePoint storage was full and new changes were being refused. When we broke the storage down, about a third of everything they were paying to store was old copies of files kept by version history, not their current files.

They weren’t alone. Over the past few months several of the businesses we look after have had SharePoint tell them they are out of space. For some it was a warning. For others, files stopped saving, OneDrive sync showed red crosses on every folder, and in one case a business-critical spreadsheet went read-only in the middle of the working day. The cause was the same almost every time. Here is what we found across our customers and how to fix it.

Fixed by Elliot Munro, CISO at GCIT. Written up by Elliot Munro, CISO.

Symptoms of SharePoint storage being full

Global and SharePoint admins receive an email from Microsoft with one of these messages:

SharePoint Online is out of storage space. Sites are in read-only mode and changes can’t be saved.

There is not enough storage space on SharePoint Online. Your storage is full. You can buy more storage or use Microsoft 365 Archive to free up storage space without deleting any data.

Staff usually notice it before anyone reads that email. What they report to us:

  • Files won’t save, with a “not enough space” error, or a shared spreadsheet suddenly opens read-only.
  • Uploads to SharePoint or Teams fail.
  • OneDrive shows red crosses on synced SharePoint folders and sync errors pile up in the sync client.
  • The SharePoint admin centre shows storage used above the total available.

A single person’s OneDrive can also go read-only when it is over that person’s own OneDrive quota. Microsoft documents these messages for that case:

This site has exceeded its maximum file storage limit. To free up space, delete files you don’t need and empty the recycle bin.

Unable to create new file. Site quota is full.

People search for this as “SharePoint storage full”, “SharePoint out of storage”, “SharePoint site read-only because of storage” or “version history taking up space in SharePoint”. They are all the same problem.

The sync client and browser can report the same cloud-storage problem differently. In another case, OneDrive displayed this message while syncing a shared SharePoint library:

There’s not enough free space in your OneDrive or shared library for this file.
OneDrive sync error: There is not enough free space in your OneDrive or shared library for this file, with identifying details redacted.
The OneDrive sync client reports a cloud-storage limit. Check whether the affected location is a personal OneDrive or a shared SharePoint library.

A browser upload to the affected SharePoint site also failed with:

Site has exceeded its maximum file storage limit
SharePoint upload error: Site has exceeded its maximum file storage limit.
The corresponding SharePoint browser-upload error. A client reset alone does not establish that the site can accept writes.

Affected Software

  • Application: SharePoint in Microsoft 365 (including Teams files), OneDrive sync app
  • Platform: Microsoft 365 Business and Enterprise plans
  • Related services: Microsoft Purview retention, Microsoft 365 Backup, PnP PowerShell

Cause: version history fills the shared storage pool

The limit has always been there

Every Microsoft 365 organisation has one shared pool of SharePoint storage: 1 TB plus 10 GB for each eligible licence, plus any extra storage you have bought. All SharePoint sites, Teams files and their recycle bins draw from that pool. OneDrive has separate quotas for each user.

For years, plenty of organisations ran over that limit without noticing anything. Microsoft’s SharePoint limits page is clear that this isn’t safe: a tenant that keeps running above its limit risks being put into read-only mode, where people can open files but can’t add or change anything until usage comes down or more storage is bought. Some of the organisations we look after had been over their limit for months with no visible effect, then staff suddenly couldn’t save files.

Microsoft is now enforcing storage limits

OneDrive has its own version of this. Microsoft 365 message MC1310684 aligned each user’s OneDrive quota with their licence, rolling out from early July to mid July 2026. Users over their licensed amount go read-only until they reduce usage or move to a licence with more storage. Microsoft explains the fix in OneDrive site is read-only because storage quota was exceeded. That change is about individual OneDrive accounts, not the shared SharePoint pool, but the message is the same: storage limits are no longer something you can ignore.

Where the space actually goes

The biggest hidden user of the pool is version history. Each time someone saves a file in a document library, SharePoint keeps the previous copy as a version, and by default it keeps up to 500 of them. A 20 MB spreadsheet saved a few times a day quietly turns into gigabytes. Every one of those versions counts against your storage.

Two other things often make it worse:

  • Recycle bins. Deleted files stay in the site recycle bin and second-stage recycle bin for up to 93 days, and they still count against your storage.
  • Retention policies and holds. If a Microsoft Purview retention policy or eDiscovery hold covers a site, version limits are ignored for the content it holds. Trimmed and deleted versions are kept in a hidden Preservation Hold Library and keep using the same storage, so a clean-up frees little or nothing until the policy is reviewed.

What we found across our customers

On 28 October 2026 we measured every Microsoft 365 organisation we manage that uses more than 50 GB of SharePoint, 63 in all. Old file versions made up about 24% of all the storage used. For the median organisation it was 18%, and in 14 organisations old versions were 40% or more of their storage.

24%of all the SharePoint storage used across 63 organisations we manage is old file versions. For the median organisation it is 18%.
  • Under 10% 25
  • 10 to 19% 9
  • 20 to 29% 6
  • 30 to 39% 9
  • 40% or more 14

Organisations, out of 63, by how much of their SharePoint storage is old file versions.

14 of 63organisations have 40% or more of their SharePoint storage in old file versions.
  • 14 at 40% or more
  • 49 under 40%

Source: SharePoint admin StorageQuotas for the Microsoft 365 organisations we manage that use 50 GB or more, snapshot taken 28 October 2026. Overall share = total version storage divided by total used storage.

  • In the worst cases, old versions were close to three-quarters of an organisation’s storage.
  • At one organisation, nearly half of a 1.6 TB tenant was version history.
  • Single libraries held hundreds of gigabytes of old versions of files that take up only a few gigabytes today.
  • Recycle bins held another 75 to 120 GB at three organisations.

At the organisations closest to their limit, the split looks like this. Of the three that were over their limit, trimming old versions alone would bring two back under it. The third is mostly current files and is still at 187% of its limit without a problem yet. We don’t expect that to last.

  • Current files
  • Old file versions

Share of each organisation’s storage limit. The dashed line is the limit (100%).

Storage used against the limit, before clean-up
OrganisationUsedCurrent filesOld versions
Customer A187%129%59%
Customer C110%89%21%
Customer E104%55%50%
Customer B98%88%10%
Customer H98%83%15%
Customer I96%66%30%
Customer G89%69%21%
Customer D88%60%28%
Customer J85%85%0%
Customer K80%66%14%

All figures are a share of each organisation’s storage limit (1 TB plus 10 GB per licence plus any add-ons). Old versions = version storage reported by Microsoft. Organisations are shown as letters. Source: SharePoint admin StorageQuotas, snapshot taken 28 October 2026.

It isn’t always versions

The same measurement also turns up other causes, and each needs a different fix:

  • Retention policies. Where a retention policy or legal hold covers SharePoint, trimming versions frees little or nothing until the hold is lifted. That is a compliance decision for the business, not a clean-up step.
  • Leftovers from migrations. At one business we found a complete copy of their old Dropbox, about 340 GB, sitting next to the real files.
  • Media. Video, photo and drawing libraries can be large with very little version history. Archiving or extra storage is usually the answer there. Customer J in the chart above has almost no version history at all, so it needs a different conversation.

At one organisation sitting at about 110% of its limit, we found roughly 340 GB of old versions and about 80 GB in recycle bins. We trimmed old versions to the current file plus one previous version and emptied the recycle bins. A day later its old versions had dropped from about 340 GB to about 100 GB, and used storage had fallen by about 315 GB, from about 110% to 90% of its limit. It is back under the limit without buying extra storage.

Resolution

Work through these steps in order. Nothing is deleted until step 4, and steps 4 and 5 can’t be undone without a backup.

1. Measure where the space has gone

SharePoint admin center shows 1.95 TB used against a 1.45 TB storage allowance.
The SharePoint admin centre during a saving failure: 1.95 TB used against a 1.45 TB allowance. This is the starting position, before cleanup.

Measure the deficit before buying temporary storage. In this case, an initial 100 GB top-up was insufficient because the tenant was already roughly 500 GB over its allowance. Read the current used and available totals, calculate the shortfall in matching units and allow room for normal writes. Get approval for any temporary capacity and its cost before ordering it.

After version cleanup and customer file deletions, the recorded usage fell below the original allowance and the temporary add-on was removed. Those were combined actions, so the total reduction cannot be attributed to version trimming alone. Before removing temporary capacity, recheck usage against the original quota and confirm that users can save current files.

In the SharePoint admin centre, go to Sites > Active sites. The storage bar at the top right shows storage used against the total for your organisation. Sort the sites by Storage used to find the biggest ones. The admin centre doesn’t include changes from the last 24 to 48 hours.

The admin centre doesn’t tell you how much of that is old versions. The same tenant figures, including version storage, come from the admin endpoint StorageQuotas():

# PowerShell 7 with PnP.PowerShell, signed in as a SharePoint Administrator
Connect-PnPOnline -Url https://contoso-admin.sharepoint.com -ClientId <your app id> -Interactive
$q = (Invoke-PnPSPRestMethod -Method Get -Url "https://contoso-admin.sharepoint.com/_api/StorageQuotas()?api-version=1.3.2").value
$q | Select-Object GeoLocation,
    @{ n = 'QuotaGB';    e = { [math]::Round($_.TenantStorageMB / 1024) } },
    @{ n = 'UsedGB';     e = { [math]::Round($_.GeoUsedStorageMB / 1024) } },
    @{ n = 'VersionsGB'; e = { [math]::Round($_.GeoUsedVersionSizeStorageMB / 1024) } }

For a breakdown by site and library (current files, old versions, recycle bins and retention holds), run the read-only sp-breakdown.ps1 script in the Scripts section below. It changes nothing.

2. Check retention policies and holds

In the Microsoft Purview portal, check Data lifecycle management > Policies > Retention policies and any eDiscovery cases for policies or holds that cover SharePoint sites. On a site, a Preservation Hold Library means retention applies or has applied. The breakdown script reports it for every site.

If retention covers the sites with the most version history, stop here and talk to the business. Removing or narrowing a retention policy is a compliance decision, not a clean-up step. Once a policy is removed or a site is excluded, Purview keeps the held content for a 30-day grace period before it is cleaned up. See how retention works for SharePoint and OneDrive.

3. Confirm backups and get sign-off

Trimmed versions are permanently deleted. They skip the recycle bin and Microsoft can’t bring them back. Before trimming, confirm whether your Microsoft 365 backup (for example Microsoft 365 Backup) includes SharePoint version history, and get written sign-off from the business owner for the trim rule you will use. The checklist under Should you do this yourself? covers what to confirm.

4. Trim old versions

Microsoft’s trim existing versions feature runs a background job on each site. With PnP PowerShell, this keeps the current file and its most recent previous version, and deletes older versions across every library on the site:

Connect-PnPOnline -Url https://contoso.sharepoint.com/sites/Projects -ClientId <your app id> -Interactive

# The current (live) version counts towards the limit: 2 = current file + 1 previous version
New-PnPSiteFileVersionBatchDeleteJob -MajorVersionLimit 2 -MajorWithMinorVersionsLimit 0

# Check progress. Large sites can take hours or days.
Get-PnPSiteFileVersionBatchDeleteJobStatus

Things to know before you run it:

  • “Access denied” usually means you aren’t a site collection admin. Being a SharePoint Administrator, or being able to read the site, isn’t enough. Batch jobs need site collection admin rights on each site. The clean-up script adds you where needed, records it and removes it again afterwards.
  • Only one version job can run per site at a time. Starting another returns “A previous work item is still in progress”.
  • Keeping only 2 versions is a deliberate choice for organisations already over their limit. Microsoft’s own settings page won’t let you set fewer than 100 versions and calls very low limits a data loss risk. Alternatives are -DeleteBeforeDays 365 (keep a year of history) or -Automatic (Microsoft’s automatic thinning).
  • Age-based trimming always deletes versions created before 1 January 2023, whatever number of days you choose. That is a documented Microsoft limitation.
  • Sites locked read-only are skipped, and versions under a retention policy are stamped with an expiry date instead of being deleted.

5. Empty the recycle bins

Once the business confirms nothing in them needs restoring, empty both stages of each site’s recycle bin:

Connect-PnPOnline -Url https://contoso.sharepoint.com/sites/Projects -ClientId <your app id> -Interactive
Get-PnPRecycleBinItem | Measure-Object Size -Sum    # what is there now
Clear-PnPRecycleBinItem -All                         # permanent: asks for confirmation

Large recycle bins often time out in PowerShell while SharePoint carries on emptying them in the background. Check again a few minutes later before running it a second time.

6. Turn on automatic version history limits

Trimming fixes today. To stop old versions building up again, turn on Microsoft’s automatic version history limits. Everything from the last 30 days is kept, then hourly, daily and weekly snapshots as files get older.

# Tenant default for new sites and libraries (admin centre connection)
Connect-PnPOnline -Url https://contoso-admin.sharepoint.com -ClientId <your app id> -Interactive
Set-PnPTenant -EnableAutoExpirationVersionTrim $true

# Each existing site: new libraries now
Connect-PnPOnline -Url https://contoso.sharepoint.com/sites/Projects -ClientId <your app id> -Interactive
Set-PnPSiteVersionPolicy -EnableAutoExpirationVersionTrim $true -ApplyToNewDocumentLibraries

# Existing libraries: only AFTER the trim job shows CompleteSuccess (one version job per site)
Set-PnPSiteVersionPolicy -EnableAutoExpirationVersionTrim $true -ApplyToExistingDocumentLibraries

7. Verify the result

  1. Run Get-PnPSiteFileVersionBatchDeleteJobStatus on each site until it reports CompleteSuccess, and note the storage released.
  2. Check the storage bar in the SharePoint admin centre, or StorageQuotas(), a day or two later. Usage figures lag the jobs by 24 to 48 hours.
  3. Confirm staff can save and upload again. OneDrive sync clients that showed red crosses don’t always recover on their own. In one case we had to reset the sync client on several PCs more than a week after storage was fixed. See Fix: OneDrive is not syncing because it is not starting.

Important Notes

Should you do this yourself?

You can, but deleted versions are gone for good. Microsoft can’t bring them back, and they don’t go to the recycle bin. Before trimming, check:

  • Do you have a Microsoft 365 backup that includes SharePoint version history?
  • Do you have legal or industry record-keeping obligations? Finance records, for example, generally need to be kept for five years. Older versions of a document are not usually the record itself, but check before you remove history someone may rely on.
  • Are any retention policies, retention labels or legal holds in place? They win, and removing them to save space is a compliance decision for the business.
  • How much history do your people actually rely on? Very low limits make it harder to undo mistakes.

Other things to know

  • Don’t unlock locked sites as part of a clean-up. A site locked read-only or set to no access was usually locked on purpose (archive, migration or legal). Find out why first.
  • Buying storage is a valid stopgap. If your tenant has gone read-only, Microsoft lets you buy extra SharePoint storage, and a “Confirm purchase” option can lift read-only mode for up to 14 days while the new capacity applies (once in a 365-day period). Microsoft 365 Archive is another option for content you must keep but rarely use.
  • Expect some clean-up after the fix. Storage figures lag by a day or two, and some OneDrive sync clients need a reset before the red crosses clear.

Scripts: SharePoint storage breakdown and version clean-up

These are the PowerShell scripts we use, made generic for any Microsoft 365 organisation. They need PowerShell 7 and PnP.PowerShell 2.12 or later, and an account with the SharePoint Administrator role. Save all three files in the same folder.

  1. Register an app once. PnP PowerShell no longer ships a shared sign-in app, so create your own with Register-PnPEntraIDAppForInteractiveLogin and note the Client ID it prints.
  2. Measure with sp-breakdown.ps1. It is read-only and writes a JSON report per site and library.
  3. Dry run sp-cleanup.ps1. Without -Execute it changes nothing and lists every change it would make.
  4. Run it for real with -Execute after sign-off. You must type the label you gave the run to confirm.
  5. Follow up the next day with -Mode Status, then -Mode ApplyPolicyToExisting -Execute once the trim jobs have finished, then -Mode RemoveAddedAdmins -Execute.
$c = @{ Name = 'Contoso'; Prefix = 'contoso'; ClientId = '<your app id>'; Tenant = 'contoso.onmicrosoft.com' }

.\sp-breakdown.ps1 @c                                   # read-only report
.\sp-cleanup.ps1 @c                                     # dry run (default): changes nothing
.\sp-cleanup.ps1 @c -Execute                            # empty bins, keep current + 1 previous version, set policy for new libraries
.\sp-cleanup.ps1 @c -Mode Status                        # next day: job progress and storage released
.\sp-cleanup.ps1 @c -Mode ApplyPolicyToExisting -Execute
.\sp-cleanup.ps1 @c -Mode RemoveAddedAdmins -Execute

Defaults are deliberately cautious. The clean-up script skips sites with a Preservation Hold Library, locked or archived sites, OneDrive and any site where a version job is already running, and it logs every change to a JSON report. Test it in a small site first. These scripts are provided as a sample without warranty.

SPStorage.Common.ps1 (340 lines): shared sign-in, retry and safety helpers
<#
SPStorage.Common.ps1 - shared helpers for sp-breakdown.ps1 and sp-cleanup.ps1.
Dot-source it. Don't run it on its own. Keep all three files in the same folder.

Published by GCIT (gcit.com.au) as a sample. Test it in your own tenant first. No warranty.

WHAT IS IN HERE
  Connect-SPOStorageSession  Signs in (see "Sign-in modes"), connects to the SharePoint admin centre and
                             returns a session object.
  Connect-SPOStorageSite     Connects to one site with the same sign-in. With -RequireSiteAdmin it makes sure
                             the signed-in admin is a site collection admin.
  Invoke-SPORetry            Retries read-only or idempotent calls when SharePoint throttles (429/503) or times out.
  Get-SPOTenantStorage       Calls the admin endpoint /_api/StorageQuotas() (the real tenant numbers).
  Get-SPOSiteSkipReason      Decides whether a site should be left alone (locked, archived, system, other host).
  Get-SPOPreservationHold    Checks whether a site has a Preservation Hold Library (retention applies).
  New-SPOLog / Add-SPOLog    Simple run log, written to JSON at the end.

REQUIREMENTS
  PowerShell 7 and PnP.PowerShell 2.12 or later (tested with 3.1.0):  Install-Module PnP.PowerShell -Scope CurrentUser

SIGN-IN MODES (-AuthMode)
  Interactive  An admin signing in to their own tenant in a browser, through YOUR OWN Entra app registration.
               Since September 2024 PnP PowerShell no longer ships a shared multi-tenant app, so -ClientId is
               required. Create one once per tenant:
                   Register-PnPEntraIDAppForInteractiveLogin -ApplicationName "PnP Storage Tool" `
                       -Tenant contoso.onmicrosoft.com -SharePointDelegatePermissions AllSites.FullControl
               It opens a browser, creates the app, asks a Global Administrator to consent and prints the
               Client ID. The person who signs in later must hold SharePoint Administrator (or Global
               Administrator). Delegated sign-in does NOT give you access to every site, which is why this file
               has the site-admin logic (see "Site admin" below).
  DeviceLogin  Same as Interactive, for a machine without a browser. On the app registration, turn on
               "Allow public client flows" (Authentication blade).
  Certificate  Unattended app-only runs: -ClientId plus -Thumbprint (certificate in CurrentUser\My or
               LocalMachine\My) or -CertificatePath (+ -CertificatePassword), and -Tenant
               (contoso.onmicrosoft.com or the tenant ID). The app needs the SharePoint APPLICATION permission
               Sites.FullControl.All (under "SharePoint", not "Microsoft Graph"), with admin consent. SharePoint
               rejects app-only with a client secret, so it must be a certificate. App-only already has full
               control of every site, so no site-admin elevation happens.
  Auto         (default) Certificate if -ClientId and a certificate were given, else Interactive if -ClientId
               was given, else stop with help.

SITE ADMIN (the most common "Access denied" cause)
  Being a SharePoint Administrator lets you manage sites from the admin centre. It does NOT make you a site
  collection admin of each site. Version trim jobs, recycle bin purges and site version policies need site
  collection admin. Being able to READ a site (for example as a member) is not enough either.
  Connect-SPOStorageSite -RequireSiteAdmin checks CurrentUser.IsSiteAdmin and, if false, adds the signed-in
  account as a site collection admin from the admin centre (Set-PnPTenantSite -Owners). Every account it adds is
  recorded in the session (AddedAdmins) and in the run log so it can be removed later
  (sp-cleanup.ps1 -Mode RemoveAddedAdmins). Under -WhatIf nothing is added. The site is reported as
  "would add admin" instead.
#>

$script:SPOTransientPattern = '429|503|502|504|throttl|Too many requests|temporarily unavailable|timed out|timeout|' +
                              'HttpClient\.Timeout|connection was closed|An existing connection was forcibly closed|' +
                              'The underlying connection was closed|server is busy'

function Test-SPOTransientError {
    param([Parameter(Mandatory)] $ErrorRecord)
    $msg = "$($ErrorRecord.Exception.Message) $($ErrorRecord.Exception.InnerException.Message)"
    return [bool]($msg -match $script:SPOTransientPattern)
}

function Test-SPOTimeoutError {
    param([Parameter(Mandatory)] $ErrorRecord)
    $msg = "$($ErrorRecord.Exception.Message) $($ErrorRecord.Exception.InnerException.Message)"
    return [bool]($msg -match 'timed out|timeout|HttpClient\.Timeout|TaskCanceled|A task was canceled')
}

function Invoke-SPORetry {
    <#
      Runs a script block and retries it on throttling (429/503) and timeouts, with exponential back-off
      (5, 10, 20, 40 s ...). PnP already retries some throttled calls itself. This covers the rest.
      Use it ONLY for reads and idempotent settings. Don't wrap "start a job" or "empty the recycle bin"
      in a blind retry. Those use verify-after logic in sp-cleanup.ps1.
    #>
    param(
        [Parameter(Mandatory)][scriptblock]$ScriptBlock,
        [string]$Operation = 'SharePoint call',
        [int]$MaxAttempts = 5,
        [int]$BaseDelaySeconds = 5
    )
    for ($attempt = 1; ; $attempt++) {
        try { return & $ScriptBlock }
        catch {
            if ($attempt -ge $MaxAttempts -or -not (Test-SPOTransientError $_)) { throw }
            $delay = [math]::Min(300, $BaseDelaySeconds * [math]::Pow(2, $attempt - 1))
            Write-Warning ("{0}: transient error (attempt {1}/{2}), retrying in {3}s: {4}" -f $Operation, $attempt, $MaxAttempts, $delay, $_.Exception.Message)
            Start-Sleep -Seconds $delay
        }
    }
}

function New-SPOLog {
    param([string]$Name)
    [pscustomobject]@{ Name = $Name; Entries = [System.Collections.Generic.List[object]]::new() }
}

function Add-SPOLog {
    param([Parameter(Mandatory)]$Log, [string]$Site, [string]$Step, [string]$Result, [ValidateSet('INFO', 'WARN', 'ERROR', 'SKIP', 'WHATIF')][string]$Level = 'INFO')
    $Log.Entries.Add([pscustomobject]@{ Time = (Get-Date).ToString('s'); Level = $Level; Site = $Site; Step = $Step; Result = $Result })
    $colour = @{ INFO = 'Gray'; WARN = 'Yellow'; ERROR = 'Red'; SKIP = 'DarkYellow'; WHATIF = 'Cyan' }[$Level]
    Write-Host ("[{0}] {1,-6} {2} | {3} | {4}" -f $Log.Name, $Level, $Site, $Step, $Result) -ForegroundColor $colour
}

function Get-SPOAdminUrlFromPrefix {
    param([Parameter(Mandatory)][string]$Prefix)
    "https://$($Prefix.ToLowerInvariant())-admin.sharepoint.com"
}

function Connect-SPOStorageSession {
    <#
    .SYNOPSIS
      Signs in and connects to the SharePoint admin centre. Returns a session object used by everything else.
    .EXAMPLE
      # Admin in their own tenant
      $s = Connect-SPOStorageSession -AdminUrl https://contoso-admin.sharepoint.com -ClientId <app id> -Tenant contoso.onmicrosoft.com
    .EXAMPLE
      # Unattended, certificate
      $s = Connect-SPOStorageSession -Prefix contoso -ClientId <app id> -Tenant contoso.onmicrosoft.com -Thumbprint <thumbprint>
    #>
    [CmdletBinding()]
    param(
        [string]$AdminUrl,
        [string]$Prefix,
        [ValidateSet('Auto', 'Interactive', 'DeviceLogin', 'Certificate')][string]$AuthMode = 'Auto',
        [string]$Tenant,
        [string]$ClientId,
        [string]$Thumbprint,
        [string]$CertificatePath,
        [securestring]$CertificatePassword
    )
    if ($PSVersionTable.PSVersion.Major -lt 7) { throw 'Run these scripts in PowerShell 7 (pwsh). PnP.PowerShell 2.x/3.x does not support Windows PowerShell 5.1.' }
    if (-not (Get-Module -ListAvailable PnP.PowerShell)) { throw 'PnP.PowerShell is not installed. Run: Install-Module PnP.PowerShell -Scope CurrentUser' }
    Import-Module PnP.PowerShell -ErrorAction Stop -WarningAction SilentlyContinue

    if (-not $AdminUrl -and $Prefix) { $AdminUrl = Get-SPOAdminUrlFromPrefix $Prefix }
    if (-not $AdminUrl) { throw 'Pass -AdminUrl (https://contoso-admin.sharepoint.com) or -Prefix (contoso).' }

    if ($AuthMode -eq 'Auto') {
        $AuthMode = if ($ClientId -and ($Thumbprint -or $CertificatePath)) { 'Certificate' }
                    elseif ($ClientId) { 'Interactive' }
                    else { throw 'No sign-in method. Pass -ClientId (your Entra app, see Register-PnPEntraIDAppForInteractiveLogin) for Interactive, or -ClientId with -Thumbprint/-CertificatePath for app-only.' }
    }
    if (-not $ClientId) { throw "$AuthMode mode needs -ClientId (your own Entra app registration)." }

    $session = [pscustomobject]@{
        AuthMode = $AuthMode; AdminUrl = $AdminUrl; Tenant = $Tenant; ClientId = $ClientId
        Thumbprint = $Thumbprint; CertificatePath = $CertificatePath; CertificatePassword = $CertificatePassword
        AdminConnection = $null; UserPrincipal = $null; IsAppOnly = ($AuthMode -eq 'Certificate')
        TenantHost = $null; AddedAdmins = [System.Collections.Generic.List[object]]::new()
    }
    $session.AdminConnection = Connect-SPOSiteRaw -Session $session -Url $AdminUrl

    # Smoke test: fails fast if the account isn't a SharePoint Administrator.
    $null = Invoke-SPORetry -Operation 'Read tenant settings' { Get-PnPTenant -Connection $session.AdminConnection }
    $session.TenantHost = ([Uri]$session.AdminUrl).Host -replace '-admin\.sharepoint\.com$', '.sharepoint.com'
    if (-not $session.IsAppOnly) {
        try {
            $me = Get-PnPProperty -ClientObject (Get-PnPWeb -Connection $session.AdminConnection) -Property CurrentUser -Connection $session.AdminConnection
            $session.UserPrincipal = if ($me.Email) { $me.Email } else { ($me.LoginName -split '\|')[-1] }
        } catch { Write-Verbose "Couldn't read current user from admin site: $($_.Exception.Message)" }
    }
    Write-Host ("Connected: {0} as {1} ({2})" -f $session.AdminUrl, ($(if ($session.IsAppOnly) { "app $ClientId" } else { $session.UserPrincipal })), $AuthMode)
    return $session
}

function Connect-SPOSiteRaw {
    # Plain connection to a site with the session's sign-in. No elevation.
    param([Parameter(Mandatory)]$Session, [Parameter(Mandatory)][string]$Url)
    if ($Session.AuthMode -eq 'Certificate') {
        if (-not $Session.Tenant) { throw 'Certificate mode needs -Tenant (contoso.onmicrosoft.com or the tenant ID).' }
        $p = @{ Url = $Url; ClientId = $Session.ClientId; Tenant = $Session.Tenant; ReturnConnection = $true }
        if ($Session.Thumbprint) { $p.Thumbprint = $Session.Thumbprint } else { $p.CertificatePath = $Session.CertificatePath; if ($Session.CertificatePassword) { $p.CertificatePassword = $Session.CertificatePassword } }
        return Connect-PnPOnline @p
    }
    # Interactive / DeviceLogin. PnP caches the token in this PowerShell process, so this normally doesn't prompt again.
    $p = @{ Url = $Url; ClientId = $Session.ClientId; ReturnConnection = $true }
    if ($Session.Tenant) { $p.Tenant = $Session.Tenant }
    if ($Session.AuthMode -eq 'DeviceLogin') { $p.DeviceLogin = $true } else { $p.Interactive = $true }
    return Connect-PnPOnline @p
}

function Connect-SPOStorageSite {
    <#
    .SYNOPSIS
      Connects to a site. With -RequireSiteAdmin, makes sure the signed-in account is site collection admin.
    .OUTPUTS
      [pscustomobject] Connection, IsSiteAdmin, AdminAdded (bool), WouldAddAdmin (bool, -WhatIf only), Note
    #>
    [CmdletBinding(SupportsShouldProcess)]
    param([Parameter(Mandatory)]$Session, [Parameter(Mandatory)][string]$Url, [switch]$RequireSiteAdmin, $Log)

    $r = [pscustomobject]@{ Connection = $null; IsSiteAdmin = $false; AdminAdded = $false; WouldAddAdmin = $false; Note = $null }
    $canRead = $false
    try {
        $r.Connection = Invoke-SPORetry -Operation "Connect $Url" { Connect-SPOSiteRaw -Session $Session -Url $Url }
        $web = Invoke-SPORetry -Operation "Read $Url" { Get-PnPWeb -Connection $r.Connection -Includes CurrentUser }
        $canRead = $true
        $r.IsSiteAdmin = if ($Session.IsAppOnly) { $true } else { [bool]$web.CurrentUser.IsSiteAdmin }
    } catch {
        $r.Note = "Can't read site: $($_.Exception.Message)"
    }

    if ($r.IsSiteAdmin -or -not $RequireSiteAdmin) {
        if (-not $canRead) { throw $r.Note }
        return $r
    }
    if ($Session.IsAppOnly) { throw "App-only connection can't read $Url. Check the app has SharePoint Sites.FullControl.All. $($r.Note)" }
    if (-not $Session.UserPrincipal) { throw "Not site admin on $Url and the signed-in account is unknown, so it can't be added." }

    # Read access isn't enough. Add the signed-in admin as site collection admin from the admin centre.
    if (-not $PSCmdlet.ShouldProcess($Url, "Add $($Session.UserPrincipal) as site collection admin")) {
        $r.WouldAddAdmin = $true
        if ($Log) { Add-SPOLog $Log $Url 'Site collection admin' "would add $($Session.UserPrincipal) (not admin now$(if (-not $canRead) { ', cannot read' }))" -Level WHATIF }
        if (-not $canRead) { $r.Connection = $null }
        return $r
    }
    Invoke-SPORetry -Operation "Add site admin $Url" { Set-PnPTenantSite -Identity $Url -Owners @($Session.UserPrincipal) -Connection $Session.AdminConnection }
    $Session.AddedAdmins.Add([pscustomobject]@{ Url = $Url; Upn = $Session.UserPrincipal; Time = (Get-Date).ToString('s') })
    if ($Log) { Add-SPOLog $Log $Url 'Site collection admin' "added $($Session.UserPrincipal) (remove later with -Mode RemoveAddedAdmins)" -Level WARN }
    $r.AdminAdded = $true

    # The permission change takes a few seconds to apply. Reconnect and re-check.
    for ($i = 1; $i -le 6; $i++) {
        Start-Sleep -Seconds (5 * $i)
        try {
            $r.Connection = Connect-SPOSiteRaw -Session $Session -Url $Url
            $web = Get-PnPWeb -Connection $r.Connection -Includes CurrentUser
            if ($web.CurrentUser.IsSiteAdmin) { $r.IsSiteAdmin = $true; return $r }
        } catch { Write-Verbose "Waiting for admin rights on $Url ($i): $($_.Exception.Message)" }
    }
    throw "Added $($Session.UserPrincipal) as site admin on $Url but still not admin after about 2 minutes. Try again later."
}

function Get-SPOTenantStorage {
    <#
      Tenant pooled storage from the admin endpoint StorageQuotas(). This is the number Microsoft enforces, and the
      same figure the SharePoint admin centre shows on its storage bar. Usage reports elsewhere can lag 24 to 48
      hours and don't always give the real quota. Values come back in MB. Multi-geo tenants return one row per geo.
    #>
    param([Parameter(Mandatory)]$Session)
    $res = Invoke-SPORetry -Operation 'StorageQuotas' {
        Invoke-PnPSPRestMethod -Method Get -Url "$($Session.AdminUrl)/_api/StorageQuotas()?api-version=1.3.2" -Connection $Session.AdminConnection
    }
    foreach ($g in @($res.value)) {
        $quota = [double]$g.TenantStorageMB; $used = [double]$g.GeoUsedStorageMB; $ver = [double]$g.GeoUsedVersionSizeStorageMB
        [pscustomobject]@{
            Geo = $g.GeoLocation; QuotaGB = [math]::Round($quota / 1024, 1); UsedGB = [math]::Round($used / 1024, 1)
            VersionsGB = [math]::Round($ver / 1024, 1)
            PctUsed = if ($quota) { [math]::Round(100 * $used / $quota, 1) } else { $null }
            VersionPctOfUsed = if ($used) { [math]::Round(100 * $ver / $used, 1) } else { $null }
            ArchiveGB = [math]::Round(([double]$g.GeoUsedArchiveStorageMB) / 1024, 1)
        }
    }
}

# Site templates that aren't user content or must not be touched.
$script:SPOSkipTemplates = 'SRCHCEN#0', 'APPCATALOG#0', 'SPSMSITEHOST#0', 'REDIRECTSITE#0', 'TENANTADMIN#0', 'POINTPUBLISHINGTOPIC#0', 'SPSPERS#10'

function Get-SPOSiteSkipReason {
    <#
      Returns $null if the site can be processed, or a short reason why it is skipped:
        - system templates (search centre, app catalog, redirect sites, admin)
        - LockState ReadOnly / NoAccess: an admin locked it on purpose (archive, migration, legal). Don't unlock
          it as part of a clean-up. Ask why first. (NoAdditions still allows deletes, so it is processed.)
        - Microsoft 365 Archive (ArchiveStatus not NotArchived): content can't be changed until reactivated.
        - Sites whose host isn't a *.sharepoint.com host of this tenant (legacy or bot entries, another tenant).
          Other hosts of the same tenant (for example multi-geo "contosoEUR.sharepoint.com") are processed.
        - OneDrive sites (*-my.sharepoint.com): per-user quota, not this job.
    #>
    param([Parameter(Mandatory)]$Site, [Parameter(Mandatory)]$Session)
    if ($Site.Template -in $script:SPOSkipTemplates) { return "system template $($Site.Template)" }
    if ($Site.Url -like '*/portals/hub') { return 'system hub site' }
    try { $u = [Uri]$Site.Url } catch { return "unparseable URL" }
    if ($u.Scheme -ne 'https' -or $u.Host -notlike '*.sharepoint.com') { return "host $($u.Host) is not a SharePoint Online host for this tenant" }
    if ($u.Host -like '*-my.sharepoint.com') { return 'OneDrive site' }
    if ($u.Host -ne $Session.TenantHost) {
        $tenantPrefix = $Session.TenantHost -replace '\.sharepoint\.com$', ''
        if ($u.Host -notlike "$tenantPrefix*.sharepoint.com") { return "host $($u.Host) differs from tenant host $($Session.TenantHost)" }
    }
    if ($Site.LockState -in 'ReadOnly', 'NoAccess') { return "site locked ($($Site.LockState)). Find out why before unlocking" }
    $archive = $Site.PSObject.Properties['ArchiveStatus']
    if ($archive -and $archive.Value -and "$($archive.Value)" -ne 'NotArchived') { return "archived ($($archive.Value))" }
    return $null
}

function Get-SPOPreservationHold {
    <#
      A Preservation Hold Library exists once a Purview retention policy, retention label or eDiscovery hold has
      applied to the site. While a retention policy or hold applies, version limits are ignored for that content:
      a trim job stamps an expiry date on held versions instead of deleting them, and anything users delete is
      copied into this library. Either way, little or no storage is freed until the hold is lifted. After a policy
      is removed (or the site excluded) Purview applies a 30-day grace period before held content is cleaned up.
      (learn.microsoft.com/sharepoint/document-library-version-history-limits, "Version storage behavior")
      Returns $null if there is no library, else size info.
    #>
    param([Parameter(Mandatory)]$Connection)
    $lib = Get-PnPList -Identity 'PreservationHoldLibrary' -Connection $Connection -ErrorAction SilentlyContinue
    if (-not $lib) { $lib = Get-PnPList -Connection $Connection | Where-Object Title -eq 'Preservation Hold Library' | Select-Object -First 1 }
    if (-not $lib) { return $null }
    $gb = $null
    try { $m = Get-PnPFolderStorageMetric -List $lib -Connection $Connection; $gb = [math]::Round($m.TotalSize / 1GB, 2) } catch { }
    [pscustomobject]@{ Present = $true; SizeGB = $gb; Items = $lib.ItemCount }
}

function Get-SPORecycleBinSummary {
    <# Counts and sizes both recycle bin stages. Capped at RowLimit items per stage (big bins are slow to list). #>
    param([Parameter(Mandatory)]$Connection, [int]$RowLimit = 50000)
    $first = @(Invoke-SPORetry -Operation 'List recycle bin (stage 1)' { Get-PnPRecycleBinItem -FirstStage -RowLimit $RowLimit -Connection $Connection })
    $second = @(Invoke-SPORetry -Operation 'List recycle bin (stage 2)' { Get-PnPRecycleBinItem -SecondStage -RowLimit $RowLimit -Connection $Connection })
    [pscustomobject]@{
        Items = $first.Count + $second.Count
        GB = [math]::Round((($first + $second | Measure-Object Size -Sum).Sum) / 1GB, 2)
        Capped = ($first.Count -ge $RowLimit -or $second.Count -ge $RowLimit)
    }
}

function Get-SPOVersionJobState {
    <#
      Is a version job running on this site? SharePoint allows one at a time per site: batch delete (trim) jobs,
      "apply policy to existing libraries" jobs and version usage reports all count.
      Returns Busy = $true if a batch delete or policy job is NotStarted/InProgress.
    #>
    param([Parameter(Mandatory)]$Connection)
    $trim = $null; $pol = $null; $err = $null
    try { $trim = Invoke-SPORetry -Operation 'Trim job status' { Get-PnPSiteFileVersionBatchDeleteJobStatus -Connection $Connection } } catch { $err = "trim status unreadable (site collection admin needed?): $($_.Exception.Message)" }
    try { $pol = Invoke-SPORetry -Operation 'Policy job status' { Get-PnPSiteVersionPolicyStatus -Connection $Connection } } catch { if (-not $err) { $err = "policy status unreadable: $($_.Exception.Message)" } }
    $busyStates = 'NotStarted', 'InProgress', 'New', 'Running'
    [pscustomobject]@{
        Trim = $trim; Policy = $pol; Error = $err
        Busy = ($trim -and "$($trim.Status)" -in $busyStates) -or ($pol -and "$($pol.Status)" -in $busyStates)
    }
}

function Save-SPOJson {
    # Always writes, even under -WhatIf (the report IS the output of a dry run).
    param([Parameter(Mandatory)]$Object, [Parameter(Mandatory)][string]$Path, [int]$Depth = 8)
    New-Item -ItemType Directory -Force -Path (Split-Path $Path) -WhatIf:$false | Out-Null
    $Object | ConvertTo-Json -Depth $Depth | Set-Content -LiteralPath $Path -Encoding utf8 -WhatIf:$false
}
sp-breakdown.ps1 (128 lines): read-only storage breakdown
<#
Published by GCIT (gcit.com.au) as a sample. Test it in your own tenant first. No warranty.

.SYNOPSIS
  READ-ONLY storage breakdown for ONE SharePoint Online tenant: where the space goes, per site, subsite and
  document library, split into current files vs version history, plus recycle bins, retention holds and
  version jobs. Use it before any clean-up to pick the right fix (versions / retention / migration dump / media).

.DESCRIPTION
  What it reads
    - Tenant: real quota, used and version storage from the admin endpoint StorageQuotas() (the numbers Microsoft
      enforces, the same as the storage bar in the SharePoint admin centre), and the tenant default version policy.
    - Each site >= -MinSiteGB: lock state, site version policy, recycle bin (both stages), Preservation Hold Library
      (= retention applies), any running version job, and per library: total size, current files, version
      history (total - current) and file count, including subsites.
  It changes NOTHING, except: with -AddSiteAdminIfNeeded, a delegated account that can't read a site is added as
  site collection admin (logged and saved to <OutDir>\<Name>-added-admins.json for later removal with
  sp-cleanup.ps1 -Mode RemoveAddedAdmins -OutDir <same folder>). Without that
  switch, unreadable sites are reported as "no access". -WhatIf is supported and blocks that one change.

  Prerequisites: PowerShell 7, PnP.PowerShell 2.12 or later (tested 3.1.0), SharePoint Administrator (delegated)
  or an app with SharePoint Sites.FullControl.All (certificate). Sign-in options: see SPStorage.Common.ps1.

  Big tenants take a while: Get-PnPFolderStorageMetric is one call per library. Throttling (429/503) is retried
  with back-off.

  Reading the output: VersionsGB = TotalGB - FilesGB per library. Sort the JSON by VersionsGB to find the worst
  libraries. Then:
    mostly versions                                   -> sp-cleanup.ps1 (dry run first)
    large Preservation Hold Library                   -> review retention with the business first
    one library much bigger than the rest, few versions -> a leftover migration copy or media, talk to the owner

.EXAMPLE
  .\sp-breakdown.ps1 -Name Contoso -Prefix contoso -ClientId <app id> -Tenant contoso.onmicrosoft.com
.EXAMPLE
  .\sp-breakdown.ps1 -Name Contoso -Prefix contoso -ClientId <app id> -Tenant contoso.onmicrosoft.com -AddSiteAdminIfNeeded
#>
[CmdletBinding(SupportsShouldProcess)]
param(
    [Parameter(Mandatory)][string]$Name,
    [string]$Prefix,
    [string]$AdminUrl,
    [double]$MinSiteGB = 5,
    [double]$MinLibraryGB = 0.1,
    [switch]$AddSiteAdminIfNeeded,
    [switch]$SkipLibraries,                                   # tenant + site level only (fast)

    [ValidateSet('Auto', 'Interactive', 'DeviceLogin', 'Certificate')][string]$AuthMode = 'Auto',
    [string]$Tenant,
    [string]$ClientId,
    [string]$Thumbprint,
    [string]$CertificatePath,
    [securestring]$CertificatePassword,

    [string]$OutDir = (Join-Path $PSScriptRoot 'reports')
)
$ErrorActionPreference = 'Stop'
. (Join-Path $PSScriptRoot 'SPStorage.Common.ps1')

$safeName = $Name -replace '[^\w]+', '-'
$out = Join-Path $OutDir "$safeName.json"
$log = New-SPOLog -Name $Name
$result = [ordered]@{ Tenant = $Name; AdminUrl = $null; Checked = (Get-Date).ToString('s'); Error = $null
                      Storage = $null; TenantPolicy = $null; SiteCount = $null; TotalSiteGB = $null; Skipped = @(); Sites = @() }
try {
    $session = Connect-SPOStorageSession -AdminUrl $AdminUrl -Prefix $Prefix -AuthMode $AuthMode -Tenant $Tenant `
        -ClientId $ClientId -Thumbprint $Thumbprint -CertificatePath $CertificatePath -CertificatePassword $CertificatePassword
    $result.AdminUrl = $session.AdminUrl
    try { $result.Storage = @(Get-SPOTenantStorage -Session $session) } catch { Add-SPOLog $log 'tenant' 'StorageQuotas' $_.Exception.Message -Level WARN }
    $result.TenantPolicy = Invoke-SPORetry -Operation 'Tenant policy' { Get-PnPTenant -Connection $session.AdminConnection } |
        Select-Object EnableAutoExpirationVersionTrim, MajorVersionLimit, ExpireVersionsAfterDays

    $sites = Invoke-SPORetry -Operation 'List sites' { Get-PnPTenantSite -IncludeOneDriveSites:$false -Connection $session.AdminConnection } |
        Sort-Object StorageUsageCurrent -Descending
    $result.SiteCount = @($sites).Count
    $result.TotalSiteGB = [math]::Round(($sites | Measure-Object StorageUsageCurrent -Sum).Sum / 1024, 1)

    $result.Sites = foreach ($s in ($sites | Where-Object { $_.StorageUsageCurrent / 1024 -ge $MinSiteGB })) {
        $why = Get-SPOSiteSkipReason -Site $s -Session $session
        $row = [ordered]@{ Url = $s.Url; Title = $s.Title; Template = $s.Template; UsedGB = [math]::Round($s.StorageUsageCurrent / 1024, 1)
                           LastModified = $s.LastContentModifiedDate; LockState = "$($s.LockState)"; Note = $why; Error = $null
                           SitePolicy = $null; RecycleGB = $null; RecycleItems = $null; PreservationHold = $false; HoldGB = $null
                           VersionJob = $null; VersionsGB = $null; Libraries = @() }
        Write-Host "[$Name] $($s.Url) ($($row.UsedGB) GB)$(if ($why) { " - $why" })"
        # Locked/archived sites are still worth measuring if we can read them. Hosts we don't recognise are not.
        if ($why -and $why -match '^host|unparseable|OneDrive') { [pscustomobject]$row; continue }
        try {
            $c = Connect-SPOStorageSite -Session $session -Url $s.Url -RequireSiteAdmin:$AddSiteAdminIfNeeded -Log $log
            if (-not $c.Connection) { $row.Error = 'no access (would add site admin)'; [pscustomobject]$row; continue }
            $conn = $c.Connection
            try { $p = Get-PnPSiteVersionPolicy -Connection $conn; $row.SitePolicy = if ($p.DefaultTrimMode) { "$($p.DefaultTrimMode)/$($p.MajorVersionLimit)/$($p.DefaultExpireAfterDays)d" } else { 'none (inherits tenant)' } } catch { $row.SitePolicy = 'n/a' }
            try { $rb = Get-SPORecycleBinSummary -Connection $conn; $row.RecycleGB = $rb.GB; $row.RecycleItems = "$($rb.Items)$(if ($rb.Capped) { '+' })" } catch { $row.RecycleItems = "unreadable: $($_.Exception.Message)" }
            try { $h = Get-SPOPreservationHold -Connection $conn; if ($h) { $row.PreservationHold = $true; $row.HoldGB = $h.SizeGB } } catch { }
            $js = Get-SPOVersionJobState -Connection $conn
            if ($js.Trim -and "$($js.Trim.Status)" -ne 'NoRequestFound') { $row.VersionJob = "$($js.Trim.Status) $($js.Trim.RequestTimeInUTC)" }

            if (-not $SkipLibraries) {
                $webUrls = @($s.Url) + @(Invoke-SPORetry -Operation "Subwebs $($s.Url)" { Get-PnPSubWeb -Recurse -Connection $conn } | ForEach-Object { $_.Url })
                $row.Libraries = foreach ($wu in $webUrls) {
                    $wc = if ($wu -eq $s.Url) { $conn } else { Invoke-SPORetry -Operation "Connect $wu" { Connect-SPOSiteRaw -Session $session -Url $wu } }
                    $libs = Invoke-SPORetry -Operation "Lists $wu" { Get-PnPList -Includes BaseType, Hidden, EnableVersioning, MajorVersionLimit -Connection $wc } |
                        Where-Object { $_.BaseType -eq 'DocumentLibrary' }
                    foreach ($l in $libs) {
                        try {
                            $m = Invoke-SPORetry -Operation "Metric $($l.Title)" { Get-PnPFolderStorageMetric -List $l -Connection $wc }
                            if ($m.TotalSize -lt $MinLibraryGB * 1GB) { continue }
                            [ordered]@{ Web = $wu; Library = $l.Title; MajorLimit = $l.MajorVersionLimit
                                        TotalGB = [math]::Round($m.TotalSize / 1GB, 2); FilesGB = [math]::Round($m.TotalFileStreamSize / 1GB, 2)
                                        VersionsGB = [math]::Round(($m.TotalSize - $m.TotalFileStreamSize) / 1GB, 2); Files = $m.TotalFileCount }
                        } catch { [ordered]@{ Web = $wu; Library = $l.Title; Error = $_.Exception.Message } }
                    }
                }
                $row.VersionsGB = [math]::Round((@($row.Libraries) | Where-Object { $_.VersionsGB } | ForEach-Object { $_.VersionsGB } | Measure-Object -Sum).Sum, 1)
            }
        } catch { $row.Error = $_.Exception.Message }
        [pscustomobject]$row
    }
    $result.Skipped = @($sites | ForEach-Object { $w = Get-SPOSiteSkipReason -Site $_ -Session $session; if ($w) { [ordered]@{ Url = $_.Url; Reason = $w } } })
    if ($session.AddedAdmins.Count) {
        $f = Join-Path $OutDir "$safeName-added-admins.json"
        $existing = if (Test-Path -LiteralPath $f) { @(Get-Content -LiteralPath $f -Raw | ConvertFrom-Json) } else { @() }
        Save-SPOJson -Object @($existing + $session.AddedAdmins) -Path $f
        Write-Host "[$Name] Site admin added on $($session.AddedAdmins.Count) site(s); listed in $f" -ForegroundColor Yellow
    }
} catch { $result.Error = $_.Exception.Message; Write-Warning $result.Error }
$result.Log = $log.Entries
Save-SPOJson -Object $result -Path $out
Write-Host "[$Name] done -> $out"
sp-cleanup.ps1 (400 lines): version trim, recycle bins and version policy (dry run by default)
<#
Published by GCIT (gcit.com.au) as a sample. Test it in your own tenant first. No warranty.

.SYNOPSIS
  SharePoint Online storage clean-up for ONE tenant: trims old file versions, empties recycle bins, sets version
  limits so it doesn't happen again, and reports job progress.

  *** DESTRUCTIVE with -Execute. Deleted versions and recycle bin items CANNOT be restored from Microsoft 365. ***
  Without -Execute the script is a DRY RUN: it changes nothing and reports what it would do. Keep that report.
  Default trim rule: keep the current file plus 1 previous version (-MajorVersionLimit 2).

.DESCRIPTION
  Modes
    Cleanup                (default, DESTRUCTIVE with -Execute) For every eligible site:
                             1. Empty the recycle bin, both stages (IRREVERSIBLE)            skip with -SkipRecycleBin
                             2. Set the site version policy for NEW libraries (-Policy)       reversible setting
                             3. Queue a background batch job that deletes old versions (-TrimRule)  IRREVERSIBLE
                           Also sets the tenant default version policy once (skip with -SkipTenantDefault).
    Status                 Read-only. Shows trim-job and policy-job progress per site plus tenant storage now.
    ApplyPolicyToExisting  Follow-up, run AFTER the trim jobs finish. Applies -Policy to EXISTING libraries so their
                           history stays limited. SharePoint runs one version job per site at a time, so sites whose
                           trim job is still running are skipped and reported. Rerun until none are left. Needs -Execute.
    RemoveAddedAdmins      Removes the site collection admin rights this script (or sp-breakdown.ps1) added for the
                           signed-in admin, using <Name>-added-admins.json. Run when the jobs are complete. Needs -Execute.

  Trim rules (-TrimRule, for the batch job)
    Count          (default) Keep the newest -MajorVersionLimit versions of each file. The current (live) version
                   counts towards the limit, so the default 2 = the current file + 1 previous. -MajorWithMinorVersionsLimit (default 0) is how many major versions keep their minor
                   (draft) versions. Frees the most space and leaves the least history. Microsoft's UI won't set
                   fewer than 100 versions and calls lower values a data-loss risk. 2 is a deliberate, signed-off
                   choice for tenants that are over their storage limit, not a setting to use everywhere.
    OlderThanDays  Delete versions older than -DeleteOlderThanDays (default 365, minimum 30). Keeps all recent history.
                   Frees less on files that are edited all the time. Microsoft limitation: this mode ALWAYS deletes
                   versions created before 1 Jan 2023, whatever the number of days.
    Automatic      Microsoft's automatic algorithm thins old versions by age. Keeps more history, frees less, and the
                   result is less predictable.
  The current version of a file is never deleted by any rule.

  Ongoing policy (-Policy, used by Cleanup for new libraries and by ApplyPolicyToExisting)
    Automatic (default)  Microsoft's automatic version-history limits.
    Count                Keep -PolicyMajorVersions versions (default 100). -PolicyExpireAfterDays 0 = never expire by age.

  What it will NOT touch (reported as SKIP)
    - Sites locked ReadOnly/NoAccess, archived sites, system sites, OneDrive, sites on unexpected hosts.
    - Version trimming on sites with a Preservation Hold Library (a retention policy or hold applies or applied).
      Under retention/hold, trim jobs only stamp an expiry on held versions and free nothing until the hold lifts.
      Deal with retention first, or override with -AllowHoldSites when you know the hold has been released.
    - Sites locked read-only: Microsoft suspends trimming there anyway.
    - Sites where a version job is already running ("A previous work item is still in progress").

  Prerequisites (check them BEFORE a real run)
    - Written sign-off from the business owner for the trim rule and the recycle bin purge.
    - Backup check: does your Microsoft 365 backup include SharePoint version history? If not, deleted versions are
      gone for good.
    - Retention check: Purview retention policies, retention labels, eDiscovery/litigation holds.
    - PowerShell 7 + PnP.PowerShell 2.12 or later (tested with 3.1.0).
    - Rights: SharePoint Administrator (delegated) or an app with SharePoint Sites.FullControl.All (certificate).
      Delegated runs add the signed-in admin as site collection admin where needed. See SPStorage.Common.ps1.

  Dry run: PnP cmdlets do NOT support -WhatIf themselves. This script wraps every change (tenant setting, site
  admin, recycle bin, policy, trim job, admin removal) in ShouldProcess and runs as -WhatIf unless you pass
  -Execute, so a run without -Execute changes nothing and prints "WHATIF ..." lines for each change it would make.
  The report JSON is still written.

.EXAMPLE
  # 1. Dry run (the default): changes nothing, shows what would happen
  $c = @{ Name = 'Contoso'; Prefix = 'contoso'; ClientId = '<app id>'; Tenant = 'contoso.onmicrosoft.com' }
  .\sp-cleanup.ps1 @c
.EXAMPLE
  # 2. Real run after sign-off: keep the current file + 1 previous version, empty recycle bins
  .\sp-cleanup.ps1 @c -Execute
.EXAMPLE
  # Keep a year of history instead
  .\sp-cleanup.ps1 @c -TrimRule OlderThanDays -DeleteOlderThanDays 365 -Execute
.EXAMPLE
  # 3. Next day: progress, then the follow-up policy, then remove the admin rights the script added
  .\sp-cleanup.ps1 @c -Mode Status
  .\sp-cleanup.ps1 @c -Mode ApplyPolicyToExisting -Execute
  .\sp-cleanup.ps1 @c -Mode RemoveAddedAdmins -Execute
#>
[CmdletBinding(SupportsShouldProcess, ConfirmImpact = 'Medium')]
param(
    [Parameter(Mandatory)][string]$Name,                      # label for logs and reports, e.g. the organisation
    [string]$Prefix,                                          # SharePoint prefix: https://<prefix>-admin.sharepoint.com
    [string]$AdminUrl,                                        # or the full admin URL
    [ValidateSet('Cleanup', 'Status', 'ApplyPolicyToExisting', 'RemoveAddedAdmins')][string]$Mode = 'Cleanup',
    [string[]]$SiteUrl,                                       # only these sites (default: all eligible sites)

    [ValidateSet('Count', 'OlderThanDays', 'Automatic')][string]$TrimRule = 'Count',
    [ValidateRange(1, 50000)][int]$MajorVersionLimit = 2,
    [ValidateRange(0, 50000)][int]$MajorWithMinorVersionsLimit = 0,
    [ValidateRange(30, 36500)][int]$DeleteOlderThanDays = 365,

    [ValidateSet('Automatic', 'Count')][string]$Policy = 'Automatic',
    [ValidateRange(1, 50000)][int]$PolicyMajorVersions = 100,
    [ValidateRange(0, 36500)][int]$PolicyExpireAfterDays = 0,

    [switch]$SkipRecycleBin,
    [switch]$SkipTrim,
    [switch]$SkipTenantDefault,
    [switch]$AllowHoldSites,
    [switch]$Execute,                                         # make real changes. Without it this is a dry run
    [switch]$Force,                                           # with -Execute, skip the "type the label" confirmation (unattended)

    # Sign-in (see SPStorage.Common.ps1)
    [ValidateSet('Auto', 'Interactive', 'DeviceLogin', 'Certificate')][string]$AuthMode = 'Auto',
    [string]$Tenant,
    [string]$ClientId,
    [string]$Thumbprint,
    [string]$CertificatePath,
    [securestring]$CertificatePassword,

    [string]$OutDir = (Join-Path $PSScriptRoot 'reports'),
    [int]$RecycleBinVerifyMinutes = 15
)
$ErrorActionPreference = 'Stop'
# Safe by default: without -Execute every change below is a WhatIf.
if (-not $Execute) { $WhatIfPreference = $true }
# "pwsh -File" passes 'a','b' as one string, so accept comma/space-separated lists too.
if ($SiteUrl) { $SiteUrl = @($SiteUrl | ForEach-Object { $_ -split '[,;\s]+' } | ForEach-Object { $_.Trim("'", '"') } | Where-Object { $_ }) }
. (Join-Path $PSScriptRoot 'SPStorage.Common.ps1')

$safeName = $Name -replace '[^\w]+', '-'
$stamp = Get-Date -Format 'yyyyMMdd-HHmm'
$isWhatIf = [bool]$WhatIfPreference
$log = New-SPOLog -Name $Name
$addedAdminsFile = Join-Path $OutDir "$safeName-added-admins.json"
$report = [ordered]@{ Tenant = $Name; Mode = $Mode; WhatIf = $isWhatIf; Started = (Get-Date).ToString('s'); TrimRule = $null; Policy = $null; TenantStorageBefore = $null; Sites = @() }

$session = Connect-SPOStorageSession -AdminUrl $AdminUrl -Prefix $Prefix -AuthMode $AuthMode -Tenant $Tenant `
    -ClientId $ClientId -Thumbprint $Thumbprint -CertificatePath $CertificatePath -CertificatePassword $CertificatePassword

try { $report.TenantStorageBefore = @(Get-SPOTenantStorage -Session $session) } catch { Add-SPOLog $log 'tenant' 'StorageQuotas' $_.Exception.Message -Level WARN }
foreach ($g in @($report.TenantStorageBefore)) { if ($g) { Add-SPOLog $log 'tenant' 'Storage now' ("{0}: {1} GB used of {2} GB ({3}%), versions {4} GB" -f $g.Geo, $g.UsedGB, $g.QuotaGB, $g.PctUsed, $g.VersionsGB) } }

# ---------------------------------------------------------------- helpers used by several modes
function Get-TargetSites {
    $all = Invoke-SPORetry -Operation 'List sites' { Get-PnPTenantSite -IncludeOneDriveSites:$false -Connection $session.AdminConnection } |
        Sort-Object StorageUsageCurrent -Descending
    if (-not $SiteUrl) { return $all }
    # Match on URL without trailing slash (the root site is listed as https://contoso.sharepoint.com/).
    $wanted = @($SiteUrl | ForEach-Object { $_.TrimEnd('/').ToLowerInvariant() })
    $found = @($all | Where-Object { $_.Url.TrimEnd('/').ToLowerInvariant() -in $wanted })
    foreach ($w in $wanted) { if ($w -notin @($found | ForEach-Object { $_.Url.TrimEnd('/').ToLowerInvariant() })) { Add-SPOLog $log $w 'Site' 'not found in this tenant' -Level WARN } }
    return $found
}

function Save-AddedAdmins {
    if ($session.AddedAdmins.Count -eq 0) { return }
    $existing = @()
    if (Test-Path -LiteralPath $addedAdminsFile) { $existing = @(Get-Content -LiteralPath $addedAdminsFile -Raw | ConvertFrom-Json) }
    Save-SPOJson -Object @($existing + $session.AddedAdmins) -Path $addedAdminsFile
}

function Get-PolicyParams([switch]$Existing) {
    # Splat for Set-PnPSiteVersionPolicy matching -Policy.
    if ($Policy -eq 'Automatic') { $p = @{ EnableAutoExpirationVersionTrim = $true } }
    else {
        $p = @{ EnableAutoExpirationVersionTrim = $false; MajorVersions = $PolicyMajorVersions; ExpireVersionsAfterDays = $PolicyExpireAfterDays }
        if ($Existing) { $p.MajorWithMinorVersions = $MajorWithMinorVersionsLimit }
    }
    if ($Existing) { $p.ApplyToExistingDocumentLibraries = $true } else { $p.ApplyToNewDocumentLibraries = $true }
    $p
}

function Get-TrimDescription {
    switch ($TrimRule) {
        'Count' { "keep newest $MajorVersionLimit major version(s) per file, $MajorWithMinorVersionsLimit with minor versions" }
        'OlderThanDays' { "delete versions older than $DeleteOlderThanDays days" }
        'Automatic' { 'Microsoft automatic thinning' }
    }
}

function Get-PolicyDescription { if ($Policy -eq 'Automatic') { 'automatic version limits' } else { "keep $PolicyMajorVersions versions, expire after $PolicyExpireAfterDays days (0 = never)" } }

$report.TrimRule = Get-TrimDescription
$report.Policy = Get-PolicyDescription

# ================================================================ Mode: Status (read-only)
if ($Mode -eq 'Status') {
    # Default to the sites a previous Cleanup run queued jobs on; otherwise every eligible site.
    if (-not $SiteUrl) {
        $lastLog = Get-ChildItem -Path $OutDir -Filter "$safeName-cleanup-*.json" -ErrorAction SilentlyContinue |
            Where-Object Name -notlike '*-whatif.json' | Sort-Object LastWriteTime | Select-Object -Last 1
        if ($lastLog) {
            $SiteUrl = @((Get-Content $lastLog.FullName -Raw | ConvertFrom-Json).Log | Where-Object { $_.Step -eq 'Batch trim job' -and $_.Level -eq 'INFO' } | ForEach-Object { $_.Site } | Select-Object -Unique)
            Write-Host "Checking $($SiteUrl.Count) site(s) from $($lastLog.Name). Pass -SiteUrl to choose others."
        }
    }
    $rows = foreach ($s in (Get-TargetSites)) {
        if (Get-SPOSiteSkipReason -Site $s -Session $session) { continue }
        $row = [ordered]@{ Url = $s.Url; UsedGB = [math]::Round($s.StorageUsageCurrent / 1024, 1); Trim = $null; Requested = $null; Completed = $null
                           VersionsDeleted = $null; ReleasedGB = $null; PolicyJob = $null; Error = $null }
        try {
            $c = Connect-SPOStorageSite -Session $session -Url $s.Url
            $st = Get-SPOVersionJobState -Connection $c.Connection
            if ($st.Trim) {
                $row.Trim = "$($st.Trim.Status)"; $row.Requested = $st.Trim.RequestTimeInUTC; $row.Completed = $st.Trim.CompleteTimeInUTC
                $row.VersionsDeleted = $st.Trim.VersionsDeleted
                if ($st.Trim.StorageReleasedInBytes) { $row.ReleasedGB = [math]::Round([double]$st.Trim.StorageReleasedInBytes / 1GB, 1) }
                if ($st.Trim.ErrorMessage) { $row.Error = $st.Trim.ErrorMessage }
            }
            if ($st.Policy) { $row.PolicyJob = "$($st.Policy.Status)" }
            if ($st.Error -and -not $row.Error) { $row.Error = $st.Error }
        } catch { $row.Error = $_.Exception.Message }
        [pscustomobject]$row
    }
    $rows | Format-Table Url, UsedGB, Trim, Requested, Completed, VersionsDeleted, ReleasedGB, PolicyJob, Error -AutoSize | Out-String -Width 250 | Write-Host
    $released = ($rows | Where-Object ReleasedGB | Measure-Object ReleasedGB -Sum).Sum
    Write-Host ("[{0}] Released so far: {1} GB. Running: {2}. Finished: {3}. Tenant 'used' figures can lag the job by 24-48 h." -f $Name,
        [math]::Round([double]$released, 1), @($rows | Where-Object { $_.Trim -in 'NotStarted', 'InProgress' }).Count, @($rows | Where-Object Trim -eq 'CompleteSuccess').Count)
    $report.Sites = @($rows)
    Save-SPOJson -Object $report -Path (Join-Path $OutDir "$safeName-status-$stamp.json")
    return
}

# ================================================================ Mode: RemoveAddedAdmins
if ($Mode -eq 'RemoveAddedAdmins') {
    if (-not (Test-Path -LiteralPath $addedAdminsFile)) { Write-Host "Nothing to remove: $addedAdminsFile not found."; return }
    $entries = @(Get-Content -LiteralPath $addedAdminsFile -Raw | ConvertFrom-Json)
    $remaining = foreach ($e in $entries) {
        if (-not $PSCmdlet.ShouldProcess($e.Url, "Remove $($e.Upn) as site collection admin")) { Add-SPOLog $log $e.Url 'Remove site admin' "would remove $($e.Upn)" -Level WHATIF; $e; continue }
        try {
            $c = Connect-SPOStorageSite -Session $session -Url $e.Url
            $st = Get-SPOVersionJobState -Connection $c.Connection
            if ($st.Busy) { Add-SPOLog $log $e.Url 'Remove site admin' 'version job still running; kept for now' -Level SKIP; $e; continue }
            Remove-PnPSiteCollectionAdmin -Owners $e.Upn -Connection $c.Connection
            Add-SPOLog $log $e.Url 'Remove site admin' "removed $($e.Upn)"
        } catch { Add-SPOLog $log $e.Url 'Remove site admin' $_.Exception.Message -Level ERROR; $e }
    }
    if (-not $isWhatIf) {
        if (@($remaining).Count) { Save-SPOJson -Object @($remaining) -Path $addedAdminsFile } else { Remove-Item -LiteralPath $addedAdminsFile -WhatIf:$false }
    }
    $report.Log = $log.Entries
    Save-SPOJson -Object $report -Path (Join-Path $OutDir "$safeName-removeadmins-$stamp.json")
    return
}

# ================================================================ Cleanup / ApplyPolicyToExisting
if ($Mode -eq 'Cleanup' -and -not $isWhatIf -and -not $Force) {
    Write-Host ''
    Write-Host "About to PERMANENTLY delete old file versions ($(Get-TrimDescription))$(if (-not $SkipRecycleBin) { ' and empty recycle bins' }) in '$Name' ($($session.AdminUrl))." -ForegroundColor Yellow
    Write-Host 'Have you confirmed: business sign-off, backup coverage, no retention or legal hold? Run without -Execute first.' -ForegroundColor Yellow
    if ((Read-Host "Type the tenant label '$Name' to continue") -ne $Name) { Write-Host 'Cancelled.'; return }
}

if ($Mode -eq 'Cleanup' -and -not $SkipTenantDefault) {
    # Tenant default: what NEW sites (and new libraries in sites without their own policy) get. Reversible.
    $tp = if ($Policy -eq 'Automatic') { @{ EnableAutoExpirationVersionTrim = $true } }
          else { @{ EnableAutoExpirationVersionTrim = $false; MajorVersionLimit = $PolicyMajorVersions; ExpireVersionsAfterDays = $PolicyExpireAfterDays } }
    if ($PSCmdlet.ShouldProcess($session.AdminUrl, "Set tenant default version policy: $(Get-PolicyDescription)")) {
        try { Invoke-SPORetry -Operation 'Set tenant default' { Set-PnPTenant @tp -Connection $session.AdminConnection }; Add-SPOLog $log 'tenant' 'Tenant default policy' (Get-PolicyDescription) }
        catch { Add-SPOLog $log 'tenant' 'Tenant default policy' $_.Exception.Message -Level ERROR }
    } else { Add-SPOLog $log 'tenant' 'Tenant default policy' "would set: $(Get-PolicyDescription)" -Level WHATIF }
}

$sites = @(Get-TargetSites)
Add-SPOLog $log 'tenant' 'Sites' "$($sites.Count) site(s) to check (mode $Mode$(if ($isWhatIf) { ', WHATIF' }))"

foreach ($s in $sites) {
    $url = $s.Url
    $siteRow = [ordered]@{ Url = $url; UsedGB = [math]::Round($s.StorageUsageCurrent / 1024, 1); LockState = "$($s.LockState)"; Skipped = $null
                           Hold = $null; RecycleBin = $null; JobBusy = $null }
    $report.Sites += $siteRow

    $why = Get-SPOSiteSkipReason -Site $s -Session $session
    if ($why) { Add-SPOLog $log $url 'Site' $why -Level SKIP; $siteRow.Skipped = $why; continue }
    if ("$($s.LockState)" -eq 'NoAdditions') { Add-SPOLog $log $url 'Site' 'LockState NoAdditions: deletes are allowed, continuing' -Level WARN }

    # Site collection admin is required for recycle bin, policy and trim. Adds the signed-in admin if needed (not in a dry run).
    try { $c = Connect-SPOStorageSite -Session $session -Url $url -RequireSiteAdmin -Log $log }
    catch { Add-SPOLog $log $url 'Connect' $_.Exception.Message -Level ERROR; $siteRow.Skipped = 'connect failed'; continue }
    Save-AddedAdmins
    if (-not $c.Connection) { $siteRow.Skipped = 'no access (would add admin)'; continue }
    $conn = $c.Connection

    # Is a version job already running here? Only one per site; starting another fails with
    # "A previous work item is still in progress".
    $jobs = Get-SPOVersionJobState -Connection $conn
    $siteRow.JobBusy = $jobs.Busy
    if ($jobs.Error -and -not $c.WouldAddAdmin) { Add-SPOLog $log $url 'Version job' $jobs.Error -Level WARN }
    if ($jobs.Busy) {
        Add-SPOLog $log $url 'Version job' ("already running (trim: {0}, policy: {1}, requested {2}); trim/policy skipped" -f $jobs.Trim.Status, $jobs.Policy.Status, $jobs.Trim.RequestTimeInUTC) -Level SKIP
    }

    # Retention: a Preservation Hold Library means trimming frees nothing.
    $hold = $null
    try { $hold = Get-SPOPreservationHold -Connection $conn } catch { Add-SPOLog $log $url 'Hold check' $_.Exception.Message -Level WARN }
    if ($hold) {
        $siteRow.Hold = $hold
        $msg = "Preservation Hold Library present ($($hold.SizeGB) GB): retention/hold applies or was released < 30 days ago"
        if ($AllowHoldSites) { Add-SPOLog $log $url 'Retention' "$msg; continuing because -AllowHoldSites" -Level WARN }
        else { Add-SPOLog $log $url 'Retention' "$msg; version trim skipped" -Level WARN }
    }
    $trimBlocked = $jobs.Busy -or ($hold -and -not $AllowHoldSites)

    if ($Mode -eq 'ApplyPolicyToExisting') {
        if ($jobs.Busy) { continue }
        if ($PSCmdlet.ShouldProcess($url, "Apply version policy to EXISTING libraries: $(Get-PolicyDescription)")) {
            try {
                $pp = Get-PolicyParams -Existing
                Invoke-SPORetry -Operation "Policy existing $url" { Set-PnPSiteVersionPolicy @pp -Connection $conn -WarningAction SilentlyContinue }
                Add-SPOLog $log $url 'Policy (existing libraries)' "job started: $(Get-PolicyDescription). Check with -Mode Status"
            } catch {
                $lvl = if ($_.Exception.Message -match 'still in progress') { 'SKIP' } else { 'ERROR' }
                Add-SPOLog $log $url 'Policy (existing libraries)' $_.Exception.Message -Level $lvl
            }
        } else { Add-SPOLog $log $url 'Policy (existing libraries)' "would apply: $(Get-PolicyDescription)" -Level WHATIF }
        continue
    }

    # ---- 1. Recycle bin (IRREVERSIBLE). Both stages count towards storage for up to 93 days.
    if (-not $SkipRecycleBin) {
        try {
            $rb = Get-SPORecycleBinSummary -Connection $conn
            $siteRow.RecycleBin = $rb
            if ($rb.Items -eq 0) { Add-SPOLog $log $url 'Recycle bin' 'already empty' }
            elseif (-not $PSCmdlet.ShouldProcess($url, "Permanently empty recycle bin ($($rb.Items) items, $($rb.GB) GB)")) {
                Add-SPOLog $log $url 'Recycle bin' "would empty $($rb.Items)$(if ($rb.Capped) { '+' }) items, $($rb.GB) GB" -Level WHATIF
            } else {
                try {
                    Clear-PnPRecycleBinItem -All -Force -Connection $conn
                } catch {
                    # Big bins: the call often hits PnP's 100-second HttpClient timeout, but SharePoint carries on and
                    # finishes the purge. Don't treat that as a failure (and don't blindly re-run it). Check below.
                    if (-not (Test-SPOTimeoutError $_)) { throw }
                    Add-SPOLog $log $url 'Recycle bin' 'client timed out; checking whether the purge finished server-side' -Level WARN
                }
                $deadline = (Get-Date).AddMinutes($RecycleBinVerifyMinutes)
                do {
                    $after = Get-SPORecycleBinSummary -Connection $conn
                    if ($after.Items -eq 0) { break }
                    Start-Sleep -Seconds 30
                } while ((Get-Date) -lt $deadline)
                if ($after.Items -gt 0) {
                    # Leftovers are usually second-stage items. Clear that stage explicitly once.
                    try { Clear-PnPRecycleBinItem -All -SecondStageOnly -Force -Connection $conn } catch { if (-not (Test-SPOTimeoutError $_)) { throw } }
                    Start-Sleep -Seconds 30
                    $after = Get-SPORecycleBinSummary -Connection $conn
                }
                $lvl = if ($after.Items -eq 0) { 'INFO' } else { 'WARN' }
                Add-SPOLog $log $url 'Recycle bin' ("emptied {0} items, {1} GB; {2} items left{3}" -f $rb.Items, $rb.GB, $after.Items, $(if ($after.Items) { ' (rerun later or check holds)' })) -Level $lvl
            }
        } catch {
            if ($c.WouldAddAdmin) { Add-SPOLog $log $url 'Recycle bin' 'size unknown until the signed-in admin is site admin (dry run), would empty it' -Level WHATIF }
            else { Add-SPOLog $log $url 'Recycle bin' $_.Exception.Message -Level ERROR }
        }
    }

    # ---- 2. Version policy for NEW libraries on this site (a setting, reversible). Skipped while a job runs.
    if ($jobs.Busy) { Write-Verbose "Policy for new libraries skipped on $url (version job running)" }
    elseif ($PSCmdlet.ShouldProcess($url, "Set version policy for new libraries: $(Get-PolicyDescription)")) {
        try {
            $pp = Get-PolicyParams
            Invoke-SPORetry -Operation "Policy new $url" { Set-PnPSiteVersionPolicy @pp -Connection $conn -WarningAction SilentlyContinue }
            Add-SPOLog $log $url 'Policy (new libraries)' (Get-PolicyDescription)
        } catch {
            $lvl = if ($_.Exception.Message -match 'still in progress') { 'SKIP' } else { 'ERROR' }
            Add-SPOLog $log $url 'Policy (new libraries)' $_.Exception.Message -Level $lvl
        }
    } else { Add-SPOLog $log $url 'Policy (new libraries)' "would set: $(Get-PolicyDescription)" -Level WHATIF }

    # ---- 3. Batch trim job (IRREVERSIBLE). Runs in the background in SharePoint, from minutes to days.
    if ($SkipTrim -or $trimBlocked) { continue }
    if (-not $PSCmdlet.ShouldProcess($url, "Queue version trim job: $(Get-TrimDescription)")) {
        Add-SPOLog $log $url 'Batch trim job' "would queue: $(Get-TrimDescription)" -Level WHATIF; continue
    }
    try {
        switch ($TrimRule) {
            'Count' { New-PnPSiteFileVersionBatchDeleteJob -MajorVersionLimit $MajorVersionLimit -MajorWithMinorVersionsLimit $MajorWithMinorVersionsLimit -Force -Connection $conn | Out-Null }
            'OlderThanDays' { New-PnPSiteFileVersionBatchDeleteJob -DeleteBeforeDays $DeleteOlderThanDays -Force -Connection $conn | Out-Null }
            'Automatic' { New-PnPSiteFileVersionBatchDeleteJob -Automatic -Force -Connection $conn | Out-Null }
        }
        Add-SPOLog $log $url 'Batch trim job' "queued: $(Get-TrimDescription)"
    } catch {
        $m = $_.Exception.Message
        if ($m -match 'still in progress') { Add-SPOLog $log $url 'Batch trim job' "another version job is running; rerun later ($m)" -Level SKIP }
        elseif (Test-SPOTimeoutError $_) {
            # Don't resubmit blindly. Check whether SharePoint accepted the request.
            $st = (Get-SPOVersionJobState -Connection $conn).Trim
            if ($st -and "$($st.Status)" -in 'NotStarted', 'InProgress') { Add-SPOLog $log $url 'Batch trim job' "queued (confirmed after client timeout): $(Get-TrimDescription)" }
            else { Add-SPOLog $log $url 'Batch trim job' "client timeout and no job found (status $($st.Status)); rerun this site" -Level ERROR }
        }
        elseif ($m -match 'Access denied|unauthori[sz]ed|403') { Add-SPOLog $log $url 'Batch trim job' "access denied: is the account site collection admin? ($m)" -Level ERROR }
        else { Add-SPOLog $log $url 'Batch trim job' $m -Level ERROR }
    }
}

Save-AddedAdmins
$report.Finished = (Get-Date).ToString('s')
$report.AddedAdmins = $session.AddedAdmins
$report.Log = $log.Entries
$kind = if ($Mode -eq 'Cleanup') { 'cleanup' } else { 'applypolicy' }
$suffix = if ($isWhatIf) { '-whatif' } else { '' }
$out = Join-Path $OutDir "$safeName-$kind-$stamp$suffix.json"
Save-SPOJson -Object $report -Path $out
$counts = $log.Entries | Group-Object Level | ForEach-Object { "$($_.Name)=$($_.Count)" }
Write-Host "[$Name] Done ($Mode$(if ($isWhatIf) { ', DRY RUN: nothing changed. Add -Execute to make the changes' })). $($counts -join ' '). Report: $out"
if ($session.AddedAdmins.Count) { Write-Host "[$Name] Site admin added on $($session.AddedAdmins.Count) site(s). Remove later: -Mode RemoveAddedAdmins" -ForegroundColor Yellow }
if ($Mode -eq 'Cleanup' -and -not $isWhatIf) { Write-Host "[$Name] Next: -Mode Status (tomorrow), then -Mode ApplyPolicyToExisting once all jobs show CompleteSuccess." }

If SharePoint says your storage is full and you’re not sure what is safe to remove, get in touch with our team. We’ll measure your storage and show you exactly where the space has gone before anything is deleted.

Was this article helpful?
Ready to secure and simplify your IT? Talk to a GCIT expert today.