1
votes

Hello Im getting this error when executing this. Can you please help me?

foreach($item in $items)
{       
   $created = $item["Created"]
   if ($created -lt $days)
   { 
      Write-Host  "Title - " $item["Title"] "Created - " $item["Created"]

      $test = $item["ID"]
      write-host $test
      $item["ID"].DeleteObject() 
      #$item[].DeleteObject() 
   }
}   

$context.ExecuteQuery()

Method invocation failed because [System.Int32] does not contain a method named 'DeleteObject'. At F:\JoshScript\deletebydate.ps1:46 char:2 + $item["ID"].DeleteObject() + ~~~~~~~~~~~~~~~~~~~~~~~~~~ + CategoryInfo : InvalidOperation: (:) [], RuntimeException + FullyQualifiedErrorId : MethodNotFound

1
have you tried $item.DeleteObject()? could you add the line where you create $items? what type/object is it?Guenther Schmitz
Yes i tried that too but it only delete the first item.joshua maniquiz
Deleting listitems.Title - test Created - 4/2/2018 7:05:58 AM 2 The collection was modified. Enumeration operation may not execute. At F:\JoshScript\deletebydate.ps1:34 char:10 + foreach($item in $items) + ~~~~~ + CategoryInfo : OperationStopped: (:) [], InvalidOperationExcept ion + FullyQualifiedErrorId : System.InvalidOperationException items are deleted from the list.joshua maniquiz

1 Answers

1
votes

I recommend you have a look at the SharePoint PnP PowerShell cmdlets, they make lots of small tasks easier to manage.

Here's the same script using their cmdlets

Connect-PnPOnline -Url <tenant>.sharepoint.com

$listName = "Shared Documents"
$items = Get-PnPListItem -List $listName -Fields "Title","Created","ID","GUID"
$days = (Get-Date).AddDays(-7)

foreach($item in $items) 
{
    $created = $item["Created"]

    Write-Host "Item created on $created"
    if($created -gt $days) 
    {
        continue;
    }

    try
    {
        Remove-PnPListItem -List $listName -Identity $item.Id -Force -ErrorAction Stop
    }
    catch
    {
        Write-Host "Unable to delete $($item.Id) in list $listName"
    }
}

If you are running Windows 10, then simply run

Install-Module -Name SharePointPnPPowerShellOnline

and it will download and install them from here.