SharePoint Online: Bulk Delete All List Items using PowerShell
Requirement: Bulk Delete SharePoint Online List Items using PowerShell.
Delete All List Items in SharePoint Online using PowerShell:
We have a list in SharePoint Online – Office 365 site with a bunch of items. Need them to be deleted in bulk rather than deleting them one by one from SharePoint web UI. Here is the script to delete list items in bulk 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/sites/Marketing"
$ListName="LargeList"
$BatchSize = 100
#Setup Credentials to connect
$Cred = Get-Credential
Try {
#Setup the context
$Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
$Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)
#Get the List
$List=$Ctx.web.Lists.GetByTitle($ListName)
$Ctx.Load($List)
$Ctx.ExecuteQuery()
Write-host "Total Number of Items Found in the List:"$List.ItemCount
Write-Host -f Yellow -NoNewline "Deleting List Items from List '$ListName'"
#Set a Flag
$Continue = $True
While($Continue)
{
Write-Host -NoNewline -f Yellow "."
#Get List Items in Batches
$Query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery($BatchSize, "ID")
$ListItems = $List.GetItems($Query)
$Ctx.Load($ListItems)
$Ctx.ExecuteQuery()
If($ListItems.Count -gt 0)
{
#Delete List Items
for($i = $ListItems.Count-1; $i -ge 0; $i--)
{
$ListItems[$i].DeleteObject()
}
$Ctx.ExecuteQuery()
}
Else
{
$Continue = $False
}
}
Write-Host -f Green "`nAll List Items Deleted Successfully!"
}
Catch {
write-host -f Red "Error:" $_.Exception.Message
}
Please note, these list 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. Here is another PowerShell to delete all list items in SharePoint Online: Delete All Items from SharePoint Online List using PowerShell
Have you ever deleted all empty document libraries using powershell? We have a site with 5000 Document Libraries where around 65% are now empty, we would like to systematically clean up this by running a single powershell script without loosing any libraries with files in. Dom
Use this script: How to Delete a Document Library in SharePoint Online using PowerShell?