I have this script that use PnP module to delete a specific OneDrive folder but when every it do Get-PNPListItem, it getting the whole items from the List instead of specific folder that I provided so just wondering how should I fix that so that I don't have to wait too much time on getting the list item.
For simplify my question, when I run the script below, it getting all the Items from /Documents instead of a specific subfolder /PC-Offboard so the process of getting an items is really long since I have over 4 millions of item inside Documents.
So it'll be great if there is away to directly get an items from /PC-Offboard
#Config Variables
$SiteURL = "https://companyname-my.sharepoint.com/personal/d34_ks_com"
$ListName = "Documents"
$FolderServerRelativeURL = "Documents/PC-OFFBOARD/"
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 2000 -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) {
Remove-PnPListItem -List $ListName -Identity $Item.ID -Recycle -Batch $Batch
Write-host "Item Queued for deletion:"$Item.ServerRelativeURL
Invoke-PnPBatch -Batch $Batch -Details
}
Invoke-PnPBatch -Batch $Batch -Details
}
Catch {
write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}