4

Is there a quick powershell script to delete items from a list where created date is less than some date? Also, would the deleted items be in the recycle bin (in the event business team wants to restore some items).

  • Nice job finding the solution! Can you post it as an answer now? – Kit Menke Jul 29 '11 at 20:37
5

On behalf of author, the answer was found here: http://blogs.flexnetconsult.co.uk/colinbyrne/2008/02/26/PowerShellSharePointThreeWaysToDeleteAListItemIDCAMLStringMatching.aspx

[void][System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$site = new-object Microsoft.SharePoint.SPSite("http://sitecollectionURL") 
$web = $site.rootweb 
$list = $web.Lists["Name of the List"]

$caml='<Where>
        <Leq>
            <FieldRef Name="Created" />
            <Value IncludeTimeValue="TRUE" Type="DateTime">2011-12-31T02:32:20Z</Value>
        </Leq>
    </Where>'

$query=new-object Microsoft.SharePoint.SPQuery 
$query.Query=$caml | Write-Output

$items=$list.GetItems($query) 
$listItemsTotal = $items.Count;

for($x=$listItemsTotal-1;$x -ge 0; $x--)
{
        $items[$x].Delete()
}

$web.Dispose() 
$site.Dispose() 
0

This code is for better performance and (no recycle bin), if you want a bulk delete, this will be much faster. Comparing the above code with this one, this code shows that deleting basic 600 items from a list took 14 seconds; whilst it took 6 minutes and 16 seconds when using the bad coded script.

REFERENCE https://blogs.msdn.microsoft.com/ahmedamin/2017/08/03/bulk-delete-sharepoint-items-in-a-large-list-using-powershell/

$web = get-spweb "URL Here"
$list = $web.lists["LIST NAME"]
$caml='<Where>
        <Leq>
            <FieldRef Name="Created" />
            <Value IncludeTimeValue="TRUE" Type="DateTime">2018-5-31T02:32:20Z</Value>
        </Leq>
    </Where>'
$query=new-object Microsoft.SharePoint.SPQuery 
$query.Query=$caml | Write-Output
$query.ViewAttributes = "Scope='Recursive'"
$query.RowLimit = 1000
$query.ViewFields = "<FieldRef Name='ID'/>"
$query.ViewFieldsOnly = $true
do
{
   $listItems = $list.GetItems($query)
   $query.ListItemCollectionPosition = $listItems.ListItemCollectionPosition
   foreach($item in $listItems)
   {
     Write-Host "Deleting Item - $($item.Id)"
     $list.GetItemById($item.Id).delete()
   }
}
while ($query.ListItemCollectionPosition -ne $null) 
0

We can delete all files or documents from the given created dates(From Date and To Date) - from all document library in a site using the below PowerShell script:

#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"
cls



$fileName = "File_Deleting_Report"
#'yyyyMMddhhmm   yyyyMMdd
$enddate = (Get-Date).tostring("yyyyMMddhhmmss")
#$filename =  $enddate + '_VMReport.doc'  
$logFileName = $fileName +"_"+ $enddate+"_Log.txt"   
$invocation = (Get-Variable MyInvocation).Value  
$directoryPath = Split-Path $invocation.MyCommand.Path  

$directoryPathForLog=$directoryPath+"\"+"LogFiles"
if(!(Test-Path -path $directoryPathForLog))  
        {  
            New-Item -ItemType directory -Path $directoryPathForLog
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        }   


#$logPath = $directoryPath + "\" + $logFileName 

$logPath = $directoryPathForLog + "\" + $logFileName 

$isLogFileCreated = $False 



#DLL location

$directoryPathForDLL=$directoryPath+"\"+"Dependency Files"
if(!(Test-Path -path $directoryPathForDLL))  
        {  
            New-Item -ItemType directory -Path $directoryPathForDLL

        } 

#DLL location

$clientDLL=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"
$clientDLLRuntime=$directoryPathForDLL+"\"+"Microsoft.SharePoint.Client.dll"

Add-Type -Path $clientDLL
Add-Type -Path $clientDLLRuntime


#File Download location

$directoryPathForFileDownloadLocation=$directoryPath+"\"+"Downloaded Files"
if(!(Test-Path -path $directoryPathForFileDownloadLocation))  
        {  
            New-Item -ItemType directory -Path $directoryPathForFileDownloadLocation
            #Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        } 

#File Download location



function Write-Log([string]$logMsg)  
{   
    if(!$isLogFileCreated){   
        Write-Host "Creating Log File..."   
        if(!(Test-Path -path $directoryPath))  
        {  
            Write-Host "Please Provide Proper Log Path" -ForegroundColor Red   
        }   
        else   
        {   
            $script:isLogFileCreated = $True   
            Write-Host "Log File ($logFileName) Created..."   
            [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
            Add-Content -Path $logPath -Value $logMessage   
        }   
    }   
    else   
    {   
        [string]$logMessage = [System.String]::Format("[$(Get-Date)] - {0}", $logMsg)   
        Add-Content -Path $logPath -Value $logMessage   
    }   
} 




#Parameters
$siteURL="https://globalsharepoint.sharepoint.com/sites/SharePointRND/"
$listName="Documents"
$fromDate="2019-12-08"
$toDate="2019-12-12"
$downloadLocation=$directoryPathForFileDownloadLocation;
$userName = "Global-sharepoint@globalsharepoint.onmicrosoft.com"
$password = "YourSPOPassWord"
$securePassword= $password | ConvertTo-SecureString -AsPlainText -Force
$batchSize =1000

#Parameters ends here.


#Setup the Context
$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteURL)
$ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($userName, $securePassword)

  <#
  $web = $ctx.Web
  $ctx.Load($web)
  $ctx.Load($web.Webs)
  $ctx.ExecuteQuery()#>



  #The below code is for root site

$docLibraryColl=$ctx.Web.Lists
$ctx.Load($docLibraryColl)
$ctx.ExecuteQuery()

foreach($oneList in $docLibraryColl)
{

if($oneList.BaseTemplate -eq "101" -and $oneList.BaseType -eq "DocumentLibrary" -and $oneList.Hidden -eq $False -and $oneList.IsCatalog -eq $False -and $oneList.IsApplicationList -eq $False) 
{



#Get the List
$list = $ctx.Web.Lists.GetByTitle($oneList.Title)
$ctx.Load($list)
$ctx.ExecuteQuery()
$emptyString = ""
#Define CAML Query to get Files from the list in batches
$Query = New-Object Microsoft.SharePoint.Client.CamlQuery


$startDateVar=$fromDate+"T13:35:58Z"
#$startDate=Get-Date -Date $startDateVar; 
$endDateVar=$toDate+"T13:36:34Z"
#$endDate=Get-Date -Date $endDateVar;



$Query.ViewXml = "@
    <View Scope='Recursive'>
        <Query>
   <Where>
      <And>
         <Geq>
            <FieldRef Name='Created' />
            <Value IncludeTimeValue='TRUE' Type='DateTime'>$startDateVar</Value>
         </Geq>
         <Leq>
            <FieldRef Name='Created' />
            <Value IncludeTimeValue='TRUE' Type='DateTime'>$endDateVar</Value>
         </Leq>
      </And>
   </Where>
</Query>        
    </View>"



$count =0

#Get List Items in Batches
Do
{


    $ListItems = $List.GetItems($Query)
    $Ctx.Load($ListItems)
    $Ctx.ExecuteQuery()
    $ListItems.Count

    #Update Postion of the ListItemCollectionPosition
    $Query.ListItemCollectionPosition = $ListItems.ListItemCollectionPosition
    $Query.ListItemCollectionPosition

    If ($ListItems.Count -eq 0) { Break }

    $fileCount=1;

    #Update List Item
    ForEach($Item in $ListItems)
    {                    


            try
            {

              $Ctx.Load($Item.File)
              $Ctx.ExecuteQuery()

              $Item.File.DeleteObject();
              $Ctx.ExecuteQuery()              


             Write-Host $Item.File.Name "has been deleted successfully" -BackgroundColor DarkGreen




        }
        catch
        {
            $ErrorMessage = $_.Exception.Message +$file.Name
            Write-Host $ErrorMessage -BackgroundColor Red
            Write-Log $ErrorMessage 

        }       



    }
    Write-Host "============================================================="
    Write-Host $count
    Write-Host "============================================================="

}While ($Query.ListItemCollectionPosition -ne $null)

}


}

Script execution example:

enter image description here

Note:

  • In your scenario just need to change the from date and To date accordingly.

For detailed steps please refer the below article:

Delete All Files from document library for the given date – PowerShell CSOM

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.