Delete First n records from sharepoint online list using Powershell

Here i have a custom list with few views.
In perticular view display am getting list threshhold problem.
So my requirements is that when the items in list is crossing 4990 then immediatly i need to delete first 100 records from the list.

first here am getting the total records in the list, then if the cound is greter then 4990 then am getting first 100 records.
then am looping each record for deletion.

so i will not get list thresh hold prolem for my view.
here am using sharepoint cleint object model to perform this operations for sharepoint online.

I think this same code will work for onpremises also.

so for logging into sharepoint online it will not accept direct password.
we need to convert our password as securestring.

so here is my code.

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.dll"
Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"
$0 = $MyInvocation.MyCommand.Definition
$dp0 = [System.IO.Path]::GetDirectoryName($0)

$url = "https://sharepoint.com/usa/"
$username = "Username"
$password = "*******"

$securePassword = ConvertTo-SecureString $password -AsPlainText -Force
#connect/authenticate to sharepoint online and get ClientContext object...
$clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
$clientContext.Credentials = $credentials

  if(!$clientContext.ServerObjectIsNull.Value)
  {
    $web = $clientContext.Site.RootWeb
    $clientContext.Load($web)
    $clientContext.ExecuteQuery()
 
    $list=$clientContext.Web.Lists.GetByTitle('MyList')


    $clientContext.Load($list)
    $clientContext.ExecuteQuery()

 
    $query = New-Object Microsoft.SharePoint.Client.CamlQuery
    $query.ViewXml="<View><RowLimit>5000</RowLimit></View>"
    $items=$list.GetItems($query)
    $clientContext.Load($items)
    $clientContext.ExecuteQuery()
    Write-Host "Total number of ListItems: " $items.Count
    if ($items.Count -gt 4990)
    {
        $query1 = New-Object Microsoft.SharePoint.Client.CamlQuery
        $query1.ViewXml="<View><RowLimit>100</RowLimit></View>"
        $items1=$list.GetItems($query1)
        $clientContext.Load($items1)
        $clientContext.ExecuteQuery()
        if ($items1.Count -gt 0)
        {
            for ($i = $items1.Count-1; $i -ge 0; $i--)
            {
                $items1[$i].DeleteObject()
            }
            $clientContext.ExecuteQuery()
        }
    }
}

Comments

Popular posts from this blog

what is Event Cache table in sharepoint

CAML Query syntax and options in SharePoint

Change anchor link url in sharepoint calender