Delete List Items CSOM SharePoint Online

Delete all items of the list using Client Object Model with PowerShell script for Office 365 sites. When you have more items to delete, we can go for batch delete.

I would like to highlight programmatically when we delete list items, those are not moved to the Recycle Bin for the site.

Please find the below code. Hope this will help.

  1. cls  
  2. Add-Type-Path"E:\PSDLL\Microsoft.SharePoint.Client.dll"  
  3. Add-Type-Path"E:\PSDLL\Microsoft.SharePoint.Client.Runtime.dll"  
  4. $0=$MyInvocation.MyCommand.Definition  
  5. $dp0=[System.IO.Path]::GetDirectoryName($0)  
  6.   
  7. $url="https://test.sharepoint.com/sites/test/"  
  8.   
  9. $username="[email protected]"  
  10.   
  11. $password="*****"  
  12.   
  13. $securePassword=ConvertTo-SecureString$password-AsPlainText-Force  
  14. #connect/authenticate to sharepoint online and get ClientContext object...  
  15. $clientContext=New-ObjectMicrosoft.SharePoint.Client.ClientContext($url)  
  16. $credentials=New-ObjectMicrosoft.SharePoint.Client.SharePointOnlineCredentials($username,$securePassword)  
  17. $clientContext.Credentials=$credentials  
  18.   
  19.   
  20.   
  21.   if(!$clientContext.ServerObjectIsNull.Value)  
  22.   {  
  23.      $web=$clientContext.Site.RootWeb     
  24.      $clientContext.Load($web)      
  25.      $clientContext.ExecuteQuery()  
  26.       
  27.      $list=$clientContext.Web.Lists.GetByTitle('TestList')  
  28.   
  29.   
  30.      $clientContext.Load($list)      
  31.      $clientContext.ExecuteQuery()  
  32.       
  33.      $query=New-ObjectMicrosoft.SharePoint.Client.CamlQuery  
  34.      $query.ViewXml="<View><RowLimit>1000</RowLimit></View>"  
  35.      $items=$list.GetItems($query)  
  36.      $clientContext.Load($items)      
  37.     $clientContext.ExecuteQuery()  
  38.   
  39.     if ($items.Count-gt0)  
  40.     {  
  41.         for ($i=$items.Count-1; $i-ge0; $i--)  
  42.         {  
  43.             $items[$i].DeleteObject()  
  44.         }   
  45.         $clientContext.ExecuteQuery()  
  46.     }  
  47. }