Tuesday, July 12, 2022

Delete all Items from SharePoint Online List

 Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll"

Add-Type -Path "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll"

     

#Config Parameters

$SiteURL="SharePoint Site URL"

$ListName="List Name"

$BatchSize = 500

   

#Setup Credentials to connect

$Cred = Get-Credential

   

Try {

    #Setup the context

    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)

    $Ctx.Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.UserName,$Cred.Password)

   

    #Get the web and List

    $Web = $Ctx.Web

    $List=$web.Lists.GetByTitle($ListName)

    $Ctx.Load($List)

    $Ctx.ExecuteQuery()

    Write-host "Total Number of Items Found in the List:"$List.ItemCount

  

    #Define CAML Query to get list items in batches

    $Query = New-Object Microsoft.SharePoint.Client.CamlQuery

    $Query.ViewXml = "<View Scope='RecursiveAll'><RowLimit Paged='TRUE'>$BatchSize</RowLimit></View>"

  

    Do {  

        #Get items from the list in batches

        $ListItems = $List.GetItems($Query)

        $Ctx.Load($ListItems)

        $Ctx.ExecuteQuery()

          

        #Exit from Loop if No items found

        If($ListItems.count -eq 0) { Break; }

  

        Write-host Deleting $($ListItems.count) Items from the List...

  

        #Loop through each item and delete

        ForEach($Item in $ListItems)

        {

            $List.GetItemById($Item.Id).DeleteObject()

        } 

        $Ctx.ExecuteQuery()

  

    } While ($True)

  

    Write-host -f Green "All Items Deleted!"

}

Catch {

    write-host -f Red "Error Deleting List Items!" $_.Exception.Message

}

No comments:

Post a Comment