SharePoint Online: Delete All List Items using PowerShell

Requirement: Delete All Items from SharePoint Online List using PowerShell
We've a list in SharePoint Online - Office 365 site with bunch of items. Need them to be deleted in bulk rather deleting one by one from SharePoint web UI. So, lets use SharePoint Online PowerShell to delete all list items.
delete all list items in sharepoint online using powershell

Delete All List Items in Bulk in SharePoint Online using PowerShell:
Here is the script to delete all list items in SharePoint online Office 365 using client side object model (CSOM) with PowerShell.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
  
#Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/"
$ListName="Projects"

$UserName="admin@crescent.com"
$Password ="Password goes here"
 
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
 
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl) 
$Context.Credentials = $credentials
  
#Get the List
$List = $Context.web.Lists.GetByTitle($ListName)
$ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery()) 
$Context.Load($ListItems)
$Context.ExecuteQuery()       

write-host "Total Number of List Items found:"$ListItems.Count

    #sharepoint online powershell delete all list items
    if ($ListItems.Count -gt 0)
    {
        #Loop through each item and delete
        For ($i = $ListItems.Count-1; $i -ge 0; $i--)
        {
            $ListItems[$i].DeleteObject()
        } 
        $Context.ExecuteQuery()
        
        Write-Host "All List Items deleted Successfully!"
    }
 
This PowerShell script deletes all items from SharePoint Online list. Please note, these items are not moved to the Recycle Bin but deleted permanently! This PowerShell script could be quite helpful when dealing with deleting bulk items from a huge list.

PowerShell to Delete All Items from Large Lists in SharePoint Online
When you have a SharePoint Online list or library with larger number of items (>5000), You may face "The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator." error. So, to mitigate this issue, lets delete list items in batch. Here is my PowerShell script to delete list items in batch.
#Load SharePoint CSOM Assemblies
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
   
#Config Parameters
$SiteURL= "https://crescent.sharepoint.com/"
$ListName="Projects"
$BatchSize = 500
 
#Setup Credentials to connect
$Cred = Get-Credential
$Cred = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
 
Try {
    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Cred
 
    #Get the web and List
    $Web=$Ctx.Web
    $List=$web.Lists.GetByTitle($ListName)
    $Ctx.Load($List)
    $Ctx.ExecuteQuery()
    Write-host "Total Number of Items Found in the List:"$List.ItemCount

    #Define CAML Query 
    $Query = New-Object Microsoft.SharePoint.Client.CamlQuery
    $Query.ViewXml = "<View><RowLimit>$BatchSize</RowLimit></View>"

    Do {  
        #Get items from the list in batches
        $ListItems = $List.GetItems($Query)
        $Ctx.Load($ListItems)
        $Ctx.ExecuteQuery()
        
        #Exit from Loop if No items found
        If($ListItems.count -eq 0) { Break; }

        Write-host Deleting $($ListItems.count) Items from the List...

        #Loop through each item and delete
        ForEach($Item in $ListItems)
        {
            $List.GetItemById($Item.Id).DeleteObject()
        } 
        $Ctx.ExecuteQuery()

    } While ($True)

    Write-host -f Green "All Items Deleted!"
}
Catch {
    write-host -f Red "Error Deleting List Items!" $_.Exception.Message
} 
This script deletes all list items in SharePoint Online using PowerShell.
The "DeleteObject()" method permanently deletes the item. Use "Recycle()" to send the item to recycle bin.

SharePoint Online PnP PowerShell to Delete All List Items
Here is the PnP PowerShell to empty list in SharePoint Online
#Config Variables
$SiteURL = "https://crescenttech.sharepoint.com/sites/marketing"
$ListName ="Records"

#Get Credentials to connect
$Cred = Get-Credential

Try {
    #Connect to PNP Online
    Connect-PnPOnline -Url $SiteURL -Credentials $Cred
    
    #Get All List Items in Batch
    $ListItems = Get-PnPListItem -List $ListName -PageSize 1000

    #Loop through List Items and Delete
    ForEach ($Item in $ListItems)
    {
        Remove-PnPListItem -List $ListName -Identity $Item.Id -Force
    }
}
catch {
    write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
Use -Recycle parameter to send the items to recycle bin instead of permanently deleting it!
SharePoint Online: Delete All List Items using PowerShell SharePoint Online: Delete All List Items using PowerShell Reviewed by Salaudeen Rajack on October 23, 2015 Rating: 5

9 comments:

  1. Hi
    Great article really helped. When running the script it gave an error when the list items are greater than 5000. Any idea how we can overcome this?

    ReplyDelete
  2. How do I delete all Files (Not Folders)?

    ReplyDelete
    Replies
    1. Add an If condition:
      If($ListItem.FileSystemObjectType -eq "File")
      {
      #Delete the Item
      }

      Delete
  3. Second script for large lists works fine except this error: "Error Deleting List Items! Exception calling "ExecuteQuery" with "0" argument(s): "The operation has timed out." It makes me execute script constantly

    ReplyDelete
    Replies
    1. Try decreasing the batch size to 100! $BatchSize = 100

      Delete
  4. Thank you for advice! I suppose error appears only at first several attempts while list had large amount of entries. After deleting several thousands, scripts started working more stably.

    ReplyDelete
  5. Great article, helped me significantly

    ReplyDelete
  6. I'm trying to use the batch mode script but it's not limiting the view, I'm still getting the

    Error Deleting List Items! Exception calling "ExecuteQuery" with "0" argument(s): "The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator."

    There are 174492 items in my sharepoint Document's folder. Please advise.

    I tried adjusting from 500 to 100 but no change.

    ReplyDelete

Please Login and comment to get your questions answered!

Powered by Blogger.