Friday, November 17, 2017

Delete list items older than date - SharePoint, PowerShell

You need to delete SharePoint items older than date? It's easy with PowerShell.


Start Sharepoint Management Shell as Administrator

 Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
     
        #Configure target site and list.
     
        $list = $($(Get-SPWeb -Identity 'https://portal/test').Lists['ListName'])
     
        #Index count for list items.
     
        $index = $list.ItemCount
     
        #Index counter for paging.
     
        $page = 0
     
        #Configure how many items to delete per batch.
     
        $pagesize = 3000
     
        #Configure how may seconds to pause between batches.
     
        $sleep = 1
     
        #Turn verbose output on/off
     
        $verbose = $true
     
        While($index -ge 0){
     
        if($verbose){
     
        $("Check item at index $($index).")
     
        }
     
        if($page -lt $pagesize){
     
        try{
     
        if($($list.Items[$index])['DateField'] -lt [DateTime]::Parse("11/7/2017")){
     
        $list.Items[$index].Delete()
     
        write-host "Deleting item at index $($index)." -foregroundcolor "green"
     
        }
     
        }
     
        catch [System.Exception]{
     
        if($verbose){
        $("Skipping item at index $($index).")
     
        }
     
        }
     
        $index--
     
        $page++
     
        }
     
        else{
     
        if($verbose){
     
        $("Sleeping for $($sleep) seconds.")
     
        }
     
        [System.Threading.Thread]::Sleep($sleep * 1000)
     
        $page = 0
     
        }
     
        }

No comments:

Post a Comment