Forum Discussion
aasenomad
Mar 10, 2022Copper Contributor
How to delete items in batch
I have this script and I'm trying to delete OneDrive business folder items in batch so that the process of deleting a really large amounts of items will be quicker but some reason the items are not actually deleted.
It saying the item is Queued for deletion in the terminal but the item is not deleted when I check in the browser.
I have over 4 millions item that I need to delete quickly as possible so I would be really appreciate if I can get any help or suggestion.
#Config Variables
$SiteURL = "https://......"
$ListName = "Documents"
$FolderServerRelativeURL = "/personal/......"
Try {
#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -UseWebLogin
$List = Get-PnPList $ListName
#Get All Items from Folder in Batch
$global:counter = 0;
$ListItems = Get-PnPListItem -List $ListName -PageSize 5000 -Fields ID,FileDirRef,FileRef -ScriptBlock `
{ Param($items) $global:counter += $items.Count; Write-Progress -PercentComplete ($global:Counter / ($List.ItemCount) * 100) -Activity `
"Getting Items from Folder '$FolderServerRelativeURL'" -Status "Getting Items $global:Counter of $($List.ItemCount)";}
#Get List Items from the folder and Sort List Items based on Server Relative URL - Descending
$ItemsFromFolder = $ListItems | Where {$_.FieldValues["FileDirRef"] -match $FolderServerRelativeURL } | Select-Object @{Name="ServerRelativeURL";Expression={$_.FieldValues.FileRef}}, ID | Sort-Object -Descending -Property ServerRelativeURL
Write-host "Total Number of Items Found in the Folder:"$ItemsFromFolder.count
#Delete List Items in Batch
$Batch = New-PnPBatch
ForEach ($Item in $ItemsFromFolder)
{
$ErrorActionPreference = "SilentlyContinue"
try{
Remove-PnPListItem -List $ListName -Identity $Item.ID -Batch $Batch -ErrorAction SilentlyContinue
Write-host "Item Queued for deletion:"$Item.ServerRelativeURL
}catch{
$ErrorActionPreference = "SilentlyContinue"
}
}
Invoke-PnPBatch -Batch $Batch -Details
}
Catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
No RepliesBe the first to reply