0

I have this code to remove the last 5 rows of a Sharepoint list and it works fine. But when i change -Last to -First it does not remove the first 5 rows. What is wrong with the code?

$SiteURL = "xxxxxxx"
$ListName = "xxxxxx"
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)
$ListItems = Get-PnPListItem -List $ListName -PageSize 2000

#Get the last 20 row items
$Items = Get-PnPListItem -List $ListName | select -Last 6
ForEach ($Item in $Items)
{
   $ItemID = $Item["ID"]   
   $ItemID
   #Remove the item and saves it in the Recycle Bin
   Remove-PnPListItem -List $ListName -Identity $ItemID -Force -Recycle
   Write-Host "Delete the Item Title : " $Item["Title"] 
}

Gr P.

7
  • How many items do you have in the list? You use pagesize on row 4 so I assume it's over the threshold, but then you get the listitems again at row 7 but without pagesize so I think you are getting the latest 5000 items and are deleting the first 5 of those. Mar 16, 2022 at 16:19
  • (Get-PnPList -Identity $ListName ).ItemCount to check the item count. If it's above 5000, you need to use PageSize so the items get's querried in batches, and then selecting -first 5 should return the right result. Mar 16, 2022 at 16:23
  • I have 586 items I wish to delete the first 6 rows for just for testing. Mar 16, 2022 at 16:24
  • Do you use any custom sort through views or such? Or is it ID 1-5 that should be deleted? Your code worked fine for me. Check that the variable $Items holds after running row 7. Mar 16, 2022 at 16:28
  • 1
    Ah, but Get-PnPListItem will always return the order of the ID and ignore any sort-orders made in SharePoint manually or through views, so you have to apply the same sorting when retrieving the items. $Items = Get-PnPListItem -List $ListName | Sort-Object DateColumn -Descending | Select-Object -First 5 Mar 16, 2022 at 16:36

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Browse other questions tagged or ask your own question.