Tuesday, November 20, 2018

Delete all items from list using Powershell script

#Load SharePoint CSOM Assemblies
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"
 
#Variables for Processing
$SiteUrl = "https://"
$ListName="ListName"

$UserName="test@cp.onmicrosoft.com"
$Password ="11111"
 
#Setup Credentials to connect
$Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($UserName,(ConvertTo-SecureString $Password -AsPlainText -Force))
 
#Set up the context
$Context = New-Object Microsoft.SharePoint.Client.ClientContext($SiteUrl)
$Context.Credentials = $credentials
 
#Get the List
$List = $Context.web.Lists.GetByTitle($ListName)
$ListItems = $List.GetItems([Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery())
$Context.Load($ListItems)
$Context.ExecuteQuery()     

write-host "Total Number of List Items found:"$ListItems.Count

    #sharepoint online powershell delete all list items
    if ($ListItems.Count -gt 0)
    {
        #Loop through each item and delete
        For ($i = $ListItems.Count-1; $i -ge 0; $i--)
        {
            $ListItems[$i].DeleteObject()
        }
        $Context.ExecuteQuery()
       
        Write-Host "All List Items deleted Successfully!"
    }

No comments:

Post a Comment