SharePoint 2012 Delete files or items from document library or list using PowerShell with conditions like created one month before


In this post, we will discuss how we can delete files or items from a document library or list which were created before 1 month or before 7 days. Suppose you have a list which is growing very larger then we can use PowerShell to delete items.


Also, read:
Delete List View using PowerShell in SharePoint 2013 and Set List View as Default view using PowerShell SharePoint 2013

Get Site Created Date using PowerShell in SharePoint 2013

Get All Attachments From SharePoint 2013 List Item using Rest API

Below the PowerShell commands to delete list items created before 1 month.

Add-PSSnapin Microsoft.SharePoint.PowerShell

$web = Get-SPWeb “http://win-pfcp2dgt8di/sites/EnjoySharePoint/”

$list = $web.Lists[“MyTestList”]

$DeleteBeforeDate = [Microsoft.SharePoint.Utilities.SPUtility]::CreateISO8601DateTimeFromSystemDateTime([DateTime]::Now.AddDays(-1))

$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()

Also you can check the below way:

Add-PSSnapin Microsoft.SharePoint.PowerShell

$web = Get-SPWeb “http://win-pfcp2dgt8di/sites/EnjoySharePoint/”

$list = $web.Lists[“MyProjectLists”];

$DeleteBeforeDate = [Microsoft.SharePoint.Utilities.SPUtility]::CreateISO8601DateTimeFromSystemDateTime([DateTime]::Now.AddDays(-1))

$caml='<Where> <Lt> <FieldRef Name=”Created” /><Value Type=”DateTime”>{0}</Value> </Lt> </Where> ‘ -f $DeleteBeforeDate

$query=new-object Microsoft.SharePoint.SPQuery

$query.Query=$caml

$collListItems=$list.GetItems($query)

$count = $collListItems.Count – 1

for($intIndex = $count; $intIndex -gt -1; $intIndex–)

{

“Deleting record: ” + $intIndex

$collListItems.Delete($intIndex);

}



Hope this will be helpful.

Check out Best Alternative to InfoPath -> Try Now

You May Also like the Following SharePoint Online Tutorials:

About Bijay Kumar

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site SharePointSky.com

View all posts by Bijay Kumar →