Delete items or files based on conditions using PowerShell in SharePoint 2013/2016

This PowerShell SharePoint tutorial, we will see how to delete items or files based on conditions in SharePoint 2013/2016.

We will see, how to 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 that is growing very larger then we can use PowerShell to delete items.

Delete SharePoint list items created before one month using PowerShell

Below the PowerShell commands to delete list items created before 1 month in SharePoint 2013/2016.

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 write the below PowerShell command to delete items created before one month in the SharePoint list or library.

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);
}

You may like following SharePoint tutorials:

This tutorial, we learned how to delete list items or files with conditions using PowerShell in SharePoint 2013/2016. Here saw here, how to delete items created before 1 month using PowerShell in SharePoint 2013/2016.

Donwload Hub site pdf

Download SharePoint Online Tutorial PDF FREE!

Get update on Webinars, video tutorials, training courses etc.

  • 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.AddMonths(-1))
    $caml=’ {0} ‘ -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()

  • >