SharePoint Tutorials

How To Cleanup SharePoint Files: Retaining Only the Latest File Versions with PowerShell

Optimize and save storage in SharePoint with my PowerShell script. Automate your management and retain only the most recent file versions effortlessly.



SharePoint has established itself as one of the leading platforms for document management and collaboration. As organizations create and manage countless files on SharePoint, it’s quite common for a single file to have multiple versions due to continuous updates. Over time, this can consume unnecessary storage and make it challenging to manage.

In this article, we’ll take a deep dive into a PowerShell script that automates the process of cleaning up old versions of files in a SharePoint document library, ensuring that only the latest version of each file is retained.

Before we proceed, please ensure that you have the following prerequisites in place:

Uninstall the Legacy SharePoint PowerShell Module

1. Open a PowerShell command prompt with administrative privileges. To do this, right-click on the Start button and select “Windows PowerShell (Admin)” or “Windows PowerShell” if you’re using an older version of Windows.

2. To uninstall the module, use the following command

Uninstall-Module -Name Microsoft.SharePoint.PowerShell
Uninstall-Module -Name Microsoft.OnlineSharePoint.PowerShell

3. Confirm the uninstallation by typing “Y” or “A” when prompted.

4. That’s it! The Legacy SharePoint PowerShell module should now be uninstalled from your system.

Installing the PowerShell 7.0 MSI package

PowerShell 7

To install PowerShell on Windows, use the following links to download the install package from GitHub.

Install Latest SharePoint Online PNP PowerShell

Install the New PnP PowerShell Module by running the command in PowerShell 7.0

Install-Module PnP.PowerShell

Once you have the prerequisites ready, follow the steps below.

Step 1: Register Azure AD Application and Grant Access to the Tenant

1. If you havent done so already, register an Azure AD Application in the Azure portal.


2. Grant appropriate permissions to the registered application to access SharePoint Online.

Step 2: Copy the Retaining Only the Latest File Versions with PowerShell Script

1. Copy and paste the following script into an editor:

# Parameters
$SiteURL = ""
$LibraryName = "Document Library Name"

# Function to clear all file versions except the latest one, folder by folder within the library.
Function Cleanup-Versions([Microsoft.SharePoint.Client.Folder]$Folder)
    Write-host "Processing Folder:" $Folder.ServerRelativeUrl -f Yellow

    # Get the Site Relative URL of the folder
    $FolderSiteRelativeURL = $Folder.ServerRelativeURL.Replace($Web.ServerRelativeURL, [string]::Empty)

    # Get all files from the folder
    $Files = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType File

    # Iterate through each file
    ForEach ($File in $Files)
        # Get file versions
        $Versions = Get-PnPProperty -ClientObject $File -Property Versions
        Write-host -f White "`tScanning File:" $File.Name

        If ($Versions.Count -gt 1) # Check if there's more than 1 version
            # Delete all versions except the latest one
            $Versions | Sort-Object -Property Created -Descending | Select-Object -Skip 1 | ForEach-Object {
            Write-Host -f Green "`t`tPrevious Versions of the File Deleted except the latest:" $File.Name

    # Get sub-folders from the folder - Exclude "Forms" and hidden folders
    $SubFolders = Get-PnPFolderItem -FolderSiteRelativeUrl $FolderSiteRelativeURL -ItemType Folder | Where {($_.Name -ne "Forms") -and (-Not($_.Name.StartsWith("_")))}
    Foreach ($SubFolder in $SubFolders)
        # Call the function recursively
        Cleanup-Versions -Folder $SubFolder

# Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive
$Web = Get-PnPWeb

# Get the root folder of the library
$RootFolder = Get-PnPList -Identity $LibraryName -Includes RootFolder | Select -ExpandProperty RootFolder

# Call the function with the root folder of the library
Cleanup-Versions -Folder $RootFolder

Step 3: Understanding the Script

  • The script begins by defining parameters $SiteURL and $LibraryName. These need to be set as per the target SharePoint site and library respectively.
  • The main function, Cleanup-Versions, takes a folder as input and processes each file within that folder, checking for versions. If a file has more than one version, it deletes all versions except the latest one. This version count check is denoted by ($Versions.Count -gt 1). If you wish to retain a different number of versions, adjust the number 1 accordingly. For instance, to keep the latest three versions, you would change it to -gt 2.
  • For better visibility and user feedback, the script uses Write-host to display messages during execution.
  • A recursive approach is taken, allowing the script to navigate through all sub-folders within the document library, ensuring every file is processed.
  • The function excludes the “Forms” folder and other hidden folders by default.
  • The script uses the SharePoint PnP PowerShell module, which provides a vast set of cmdlets making it easier to perform many administrative tasks on SharePoint.

With this understanding, administrators can now easily modify the script to tailor the version retention policy as per their requirements, ensuring efficient storage use.


Managing storage efficiently and ensuring that your SharePoint sites remain clean and organized is critical for smooth operations and easy access. The above PowerShell script assists administrators in automating the process of cleaning up older versions, which can be particularly handy for large libraries or frequent document updates.

However, it’s essential to remember always to test scripts like these in a non-production environment first to ensure they work as expected and avoid any unintentional data loss.

I hope this article was helpful! You can find more here: SharePoint Articles.


Leave a Comment

Stay Informed

Receive instant notifications when new content is released.