SharePoint Online: Delete All Files Older than 30 Days in a Document Library using PowerShell

Requirement: Delete All Files Older than 30 Days in a SharePoint Online Document Library.

PowerShell to Delete All Files Older than 30 Days in a Document Library in SharePoint Online

PowerShell to Delete Files Older than 30 Days in SharePoint Online

I had to remove all files older than 30 days from a SharePoint Online document library. This PowerShell lets you remove all files created 30 days ago (or more!) from a SharePoint Online document library.

#Config Variables
$SiteURL = "https://crescent.sharepoint.com/sites/ops/"
$LibraryName = "Documents"
  
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

#Define Query to Filter Files that were 'Created' 30 days ago (or More!)
$Query= "<View Scope='RecursiveAll'>
            <Query>
                <Where>
                    <And>
                        <Lt>
                            <FieldRef Name='Created' Type='DateTime'/>
                            <Value Type='DateTime' IncludeTimeValue='TRUE'>
                                <Today OffsetDays='-30'/>
                            </Value>
                        </Lt>
                        <Eq>
                            <FieldRef Name='FSObjType' /><Value Type='Integer'>0</Value>
                        </Eq>
                    </And>
                </Where>
            </Query>
        </View>"

#Get All Files matching the query 
$Files = Get-PnPListItem -List $LibraryName -Query $Query -PageSize 500
  
#Loop through each File
Write-host -f Green "Total Number of Files Found:"$Files.Count
ForEach($File in $Files)
{ 
    #Send File to recycle bin
    Write-Host "Deleting File Created On:" $File.FieldValues.Created -f Yellow
    Move-PnPListItemToRecycleBin -List $LibraryName -Identity $File.Id -Force
    Write-Host "`tDeleted File at:" $File.FieldValues.FileRef -f Green
}

Similarly, you can also delete files based on the “Modified” date!

Delete All Files Older than 1 Year in SharePoint Online site

How about deleting all files that are not updated in the past 1 Year or more? Well, The below script scans all files from all document libraries in the given site and generates a report of files older than 1 Year or more based on their last modified date. Just run this script once, Go through the CSV File it generates. Once you are confident, you can uncomment Line#36 to actually delete the files.

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/marketing"
$CSVPath = "C:\Temp\FilesDeleted.csv"
$DataCollection = @()

#Connect to SharePoint Online site
Connect-PnPOnline $SiteURL -Interactive
   
#Get all Documents Libraries from the site
$ExcludedLists  = @("Style Library", "Wiki", "Form Templates","Images","Pages","Site Pages","Preservation Hold Library","Site Assets")
$DocumentLibraries = Get-PnPList | Where {$_.Hidden -eq $False -and $_.ItemCount -gt 0 -and $ExcludedLists -notcontains $_.Title -and $_.BaseType -eq "DocumentLibrary"}

#Loop through all document libraries
ForEach ($List in $DocumentLibraries)
{
    #Get all Files that are not modified in the past 1 year or more!
    $global:counter = 0;
    $ListItems = Get-PnPListItem -List $List -PageSize 2000 -Fields Created, Modified -ScriptBlock `
        { Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete ($global:Counter / ($List.ItemCount) * 100) -Activity `
             "Getting Documents from Library '$($List.Title)'" -Status "Getting Files $global:Counter of $($List.ItemCount)";} | ` 
                 Where {$_.FileSystemObjectType -eq "File" -and $_.FieldValues.Modified -lt (Get-Date).AddDays(-365)}

    $ItemCounter = 0
    #Iterate through each item
    Foreach ($Item in $ListItems)
    {
        $DataCollection +=New-Object PSObject -Property ([Ordered] @{
            Name  = $Item.FieldValues.FileLeafRef
            RelativeURL = $Item.FieldValues.FileRef
            CreatedOn = $Item.FieldValues.Created
            ModifiedBy =  $Item.FieldValues.Editor.Email
            ModifiedOn = $Item.FieldValues.Modified
        })

        #Delete the File
        #Remove-PnPListItem -List $List -Identity $Item.ID -Recycle -Force

        $ItemCounter++
        Write-Progress -PercentComplete ($ItemCounter / ($ListItems.Count) * 100) -Activity "Deleting Files from Library '$($List.Title)' $ItemCounter of $($ListItems.Count)" -Status "Deleting file '$($Item['FileLeafRef'])"        
    }
}
#Export data to CSV File
$DataCollection | Export-Csv -Path $CSVPath -NoTypeInformation

Salaudeen Rajack

Salaudeen Rajack - SharePoint Expert with Two decades of SharePoint Experience. Love to Share my knowledge and experience with the SharePoint community, through real-time articles!

6 thoughts on “SharePoint Online: Delete All Files Older than 30 Days in a Document Library using PowerShell

  • Hello Salaudeen
    Great scripts you are share here with us !

    For the second script, can you somehow increase speed in using the batch method ? Can you combine that ?

    Reply
  • Thanks, these scripts run great! The only issue is, if there are more than 5,000 items in the library, you get the “List threshold” error. I see you have processed the retrieval of all documents from a library using a batch process, would it be possible to do that with the deletion steps above too? https://www.sharepointdiary.com/2018/08/sharepoint-online-powershell-to-get-all-files-in-document-library.html

    PS, thanks for ALL of the work you have been doing on this site….you have “saved my life” more than once with all of the great tips and scripts over the years!!

    Reply
  • This is just what I was searching for. How do I get it to delete from all Libraries in a collection?

    Reply
    • Post has been updated to delete all files – based on last modified date – from all libraries!

      Reply

Leave a Reply

Your email address will not be published.