Bulk delete SharePoint List items using CSOM

  •  
  •  
  •  
  •  
  •  
  •  

SharePoint CSOM enables us to delete bulk list items using browser console.

Scenario-1:  We have a list of records to be deleted from a SharePoint list and we do not want to delete record one by one.

Scenario-2:  We want to delete the list and list already had cross the threshold limit and not allowing to delete list until records reaches under the threshold limit.

Following script demonstrates the steps to achieve the same

Step-1:  Navigate to SharePoint site where list is present.

Step-2: Open Inspect Element by clicking F12 in any browser. Open console tab.

Step-3: Copy and Paste following code in console, Insert the list name (wherever ‘ListName’ is mentioned) and run the command.

// —————————————

var clientContext;
var website;
var oList;
var cnt = 0;
// Make sure the SharePoint script file ‘sp.js’ is loaded before your code runs.
SP.SOD.executeFunc(‘sp.js’, ‘SP.ClientContext’, sharePointReady);

// Create an instance of the current context.
function sharePointReady() {
clientContext = SP.ClientContext.get_current();
website = clientContext.get_web();
oList = website.get_lists().getByTitle(‘ListName’);

var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml(‘1000’);
this.collListItem = oList.getItems(camlQuery);

clientContext.load(website);
clientContext.load(collListItem, ‘Include(Id)’);
clientContext.executeQueryAsync(Function.createDelegate(this, this.onQuerySucceeded), Function.createDelegate(this, this.onQueryFailed));
}

function onQuerySucceeded(sender, args) {

var listItemInfo = ”;
var listItemEnumerator = collListItem.getEnumerator();

while (listItemEnumerator.moveNext()) {
var oListItem = listItemEnumerator.get_current();
var ID = oListItem.get_id();
var oListItemDel = oList.getItemById(ID);
oListItemDel.deleteObject();
clientContext.executeQueryAsync(Function.createDelegate(this, this.onDeleteSucceeded), Function.createDelegate(this, this.onDeleteFailed));
console.log(ID + ” : Deleted”);
}
}

function onQueryFailed(sender, args) {
console.log(‘Request failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}

function onDeleteFailed(sender, args) {
console.log(‘Delete failed. ‘ + args.get_message() + ‘\n’ + args.get_stackTrace());
}

function onDeleteSucceeded(sender, args) {
cnt = cnt + 1;
console.log(‘Delete success : ‘ + cnt);
}

// —————————————

Note: Above script delete 1000 records at a time.

Download JS file link -> DeleteBulkListItem

Leave a Reply

Your email address will not be published.

twenty − 17 =