SharePoint Online: Bulk Delete Files from a CSV using PowerShell

Requirement: Delete multiple files from SharePoint Online document libraries from a CSV using PowerShell.

How to Delete Multiple Files in SharePoint Online Site from a CSV file?
We have a CSV file with a list of URLs of various files in multiple document libraries in SharePoint Online. I wanted to bulk delete them. Here is my CSV file format: It has "FileName" and "ServerRelativeURL" as columns.
powershell to bulk delete files in sharepoint online

You can download the CSV template at: CSV to Bulk Delete Files in SharePoint Online

PowerShell to Remove Files using a CSV file in SharePoint Online:
This PowerShell script deletes each file from the CSV file in a given site.
$SiteURL = ""
$CSVFilePath = "C:\Temp\BulkDeleteFiles.csv"

#Get Credentials to connect
$Cred = Get-Credential

Try {
    #Connect to PnP Online
    Connect-PnPOnline -Url $SiteURL -Credentials $Cred

    #Read from CSV file and delete
    Import-CSV $CSVFilePath | ForEach-Object {
        #Check if File exists
        $File = Get-PnPFile -ServerRelativeUrl $_.ServerRelativeUrl -ErrorAction SilentlyContinue 
            #Delete the File - Send to Recycle bin without prompting
            Remove-PnPFile -ServerRelativeUrl $_.ServerRelativeURL -Recycle -Force
            Write-Host "Deleted File '$($_.FileName)' at $($_.ServerRelativeUrl)" -ForegroundColor Green
            Write-Host "File '$($_.FileName)' doesn't exists at $($_.ServerRelativeUrl)" -ForegroundColor Yellow
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red

No comments:

Please Login and comment to get your questions answered!

Powered by Blogger.