Dear All

Kindly find below the script to delete items from SharePoint list using CAML Query.

The outcome of the below script is to delete items that are created 7 days before:

Add-PSSnapin Microsoft.SharePoint.PowerShell

[System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$web = Get-SPWeb "YOUR SHAREPOINT SITE"
$list = $web.Lists["YOUR LIST NAME"]
$DeleteBeforeDate = [Microsoft.SharePoint.Utilities.SPUtility]::CreateISO8601DateTimeFromSystemDateTime([DateTime]::Now.AddDays(-7))
$caml='<Where> <Lt> <FieldRef Name="Created" /><Value Type="DateTime">{0}</Value> </Lt> </Where> ' -f $DeleteBeforeDate
$query=new-object Microsoft.SharePoint.SPQuery
$query.Query=$caml
$col=$list.GetItems($query)
Write-Host $col.Count
$col | % {$list.GetItemById($_.Id).Delete()}
$web.Dispose()

Below you will find the PowerShell file (CorrectOne.ps1) and batch file to run the PowerShell file:

 DeleteScript.rar
Add-PSSnapin Microsoft.SharePoint.PowerShell

[System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$web = Get-SPWeb "YOUR SHAREPOINT SITE"
$list = $web.Lists["YOUR LIST NAME"]
$DeleteBeforeDate = [Microsoft.SharePoint.Utilities.SPUtility]::CreateISO8601DateTimeFromSystemDateTime([DateTime]::Now.AddDays(-7))
$caml='<Where> <Lt> <FieldRef Name="Created" /><Value Type="DateTime">{0}</Value> </Lt> </Where> ' -f $DeleteBeforeDate
$query=new-object Microsoft.SharePoint.SPQuery
$query.Query=$caml
$col=$list.GetItems($query)
Write-Host $col.Count
$col | % {$list.GetItemById($_.Id).Delete()}
$web.Dispose()

Add-PSSnapin Microsoft.SharePoint.PowerShell

[System.reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")
$web = Get-SPWeb "YOUR SHAREPOINT SITE"
$list = $web.Lists["YOUR LIST NAME"]
$DeleteBeforeDate = [Microsoft.SharePoint.Utilities.SPUtility]::CreateISO8601DateTimeFromSystemDateTime([DateTime]::Now.AddDays(-7))
$caml='<Where> <Lt> <FieldRef Name="Created" /><Value Type="DateTime">{0}</Value> </Lt> </Where> ' -f $DeleteBeforeDate
$query=new-object Microsoft.SharePoint.SPQuery
$query.Query=$caml
$col=$list.GetItems($query)
Write-Host $col.Count
$col | % {$list.GetItemById($_.Id).Delete()}
$web.Dispose()



See Also



Other Languages

This article is also available in the following languages: