Delete all items from a SharePoint Online list using PnP PowerShell - SPGuides (2022)

Delete all items from a SharePoint Online list using PnP PowerShell - SPGuides (1)

In this PnP PowerShell tutorial, we will discuss, how to delete all items from a SharePoint Online list using PnP PowerShell.

We will see, how to delete list items created before N days using PowerShell in SharePoint Online.

If you are new to PnP PowerShell, you can read an article on How to connect SharePoint Online using PnP PowerShell.

Here, I got a requirement to delete more than 10000 items from a SharePoint Online list.

I used PnP PowerShell to delete items from the SharePoint Online list.

Below is the PowerShell command to remove all items from a SharePoint Online list using PnP PowerShell, you can write, debug and test the script using PowerShell ISE.

Connect-PnPOnline –Url https://tsinfo.sharepoint.com/sites/sharepointsky/$items =Get-PnPListItem -List "Budgets" -PageSize 500foreach ($item in $items){try{Remove-PnPListItem -List "Budgets" -Identity $item.Id -Force}catch{Write-Host "Error Occurred While Deleting the Item from the SharePoint Online List"}}

This will delete all the items from the list.

It will take really good amount of time if it is a large list, or is having more items in the SharePoint list.

Here I have added the -PageSize 500 attribute.

(Video) How to delete all items from SharePoint list Power Automate

Get-PnPListItem : The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator

If you will not use the -PageSize attribute, then you will get the error like below:

Get-PnPListItem : The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.

Delete all items from a SharePoint Online list using PnP PowerShell - SPGuides (2)

The above error comes because of the SharePoint list view threshold issue. To fix the error you can add the -PageSize like below:

$items =Get-PnPListItem -List "Budgets" -PageSize 10000

This is how to fix the error, get-pnplistitem : the attempted operation is prohibited because it exceeds the list view threshold.

Read: SharePoint PnP PowerShell examples

Now, let us see, how todelete all items from the SharePoint list programmatically javascript object model (jsom) in SharePoint Online.

In SharePoint Online we can only use client-side object model code, we can not use any server-side code.

In this particular example, we got a requirement to delete all items from a SharePoint online list using the JavaScript object model (jsom).

Here we are using a SharePoint online site Office 365 but the same code will also work for SharePoint 2016 and SharePoint 2013.

In this jsom example I have taken a button and on click of that button it will delete all items from a list known as “SourceList”. And I have added the jsom code inside a script editor web part which we have put inside a web part page in SharePoint Online.

If you are new to JSOM (JavaScript Object Model), then you can download a FREE PDF Of 51 JSOM Examples in SharePoint Online.

Here in the CAML query, we are passing the RowLimit as 100, you can provide as per the requirement.

Delete all items from SharePoint list programmatically javascript client object model (jsom)

(Video) Check if a list exists in SharePoint Online site using PNP PowerShell

Below is the full JavaSctipt Object model code todelete all items from the sharepoint list programmatically.

<input type="button" id="btnSubmit" value="Delete All Items" /><br/><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script><script>$(function () {bindButtonClick();});function bindButtonClick() {$("#btnSubmit").on("click", function () {deleteAllItemsFromList();});}var clientContext;var website;var oList;var cnt = 0;function deleteAllItemsFromList() {clientContext = SP.ClientContext.get_current();website = clientContext.get_web();oList = website.get_lists().getByTitle('SourceList');var camlQuery = new SP.CamlQuery();camlQuery.set_viewXml('<View><RowLimit>100</RowLimit></View>');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));}}function onQueryFailed(sender, args) {alert('Failed');}function onDeleteFailed(sender, args) {alert('Failed');}function onDeleteSucceeded(sender, args) {cnt = cnt + 1;alert('Delete success : ' + cnt);}</script>

Once you will save the code and click on the button to delete, it will display an alert on each item delete like below:

Delete all items from a SharePoint Online list using PnP PowerShell - SPGuides (3)

Here, we saw, how todelete all items from sharepoint list programmatically javascript or jsom in SharePoint Online or SharePoint 2019/2016/2013.

Now, let us see how to all list items using PnP in SharePoint Online. The same pnp code we can use to delete list items from SharePoint 2013, SharePoint 2016 and SharePoint 2019.

If you are new to pnp SharePoint Online, read SharePoint Online Development using Patterns and Practices (PnP).

SharePoint online pnp delete list items

On my SharePoint Online site, I have a list name called “Order Details” with few items. We will see how we can delete all items from this SharePoint Online list programmatically using PnP core CSOM library code.

Delete all items from a SharePoint Online list using PnP PowerShell - SPGuides (4)

The below references we have to use in the code to work with PnP libraries:

  • Microsoft.SharePoint.Client
  • OfficeDevPnP.Core

Here I have created an asp.net application and I have added a button. Just click on the button, it will Delete all items from the list of SharePoint Online using the PnP core CSOM library.

<div><asp:Button ID="btnDeleteItems" runat="server" Text="Delete Items From the List" OnClick="btnDeleteItems_Click" /><br /><asp:Label ID="lblDeleteItems" runat="server" Text=""></asp:Label></div>

Below given snippet code is delete all items from the list of SharePoint online using PnP.

(Video) How to remove SharePoint Online Site Collection Administrator (Browser, PowerShell & PnP PowerShell)

AuthenticationManager authMgr = new AuthenticationManager();string siteURL = https://DomainName.sharepoint.com/sites/TSInfoPNP";string userName = "*******@DomainName.onmicrosoft.com";string password = "******";protected void btnDeleteItems_Click(object sender, EventArgs e){deleteItemsInList();}void deleteItemsInList(){try{using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteURL, userName, password)){List oList = ctx.Web.GetListByTitle("Order Details");ctx.ExecuteQueryRetry();CamlQuery query = CamlQuery.CreateAllItemsQuery(4000);Microsoft.SharePoint.Client.ListItemCollection items = oList.GetItems(query);ctx.Load(items);ctx.ExecuteQuery();for (int i = items.Count - 1; i >= 0; i--){items[i].DeleteObject();}ctx.ExecuteQuery();lblDeleteItems.Text = "All Items Deleted from the List Successfully";}}catch (Exception ex){}}

Run your application and click on button on the page.

Delete all items from a SharePoint Online list using PnP PowerShell - SPGuides (5)

Go and check your SharePoint Online list all the items are deleted as shown below.

Delete all items from a SharePoint Online list using PnP PowerShell - SPGuides (6)

Here, we learned, how to delete all items programmatically from list of SharePoint Online using the PnP core CSOM Library. Here, we see an example on SharePoint online pnp delete list items.

In SharePoint Online, you might get some requirement to delete items that are created 30 days before or items that are created in the last 10 days like this.

First, we will discuss how we can delete items created in last 7 days using PowerShell in SharePoint online.

Here I have alist in my SharePoint online site which has 3 items inside it, one item created a few days back and other two items created yesterday only. See the fig below:

Delete all items from a SharePoint Online list using PnP PowerShell - SPGuides (7)

Now according to our requirement, it should delete those two items which are created yesterday, because those two items only fall into items created in last 7 days condition.

In the PowerShell we have used CAML and we add filter using OffsetDays=-7 like below:

$caml = '<View><Query><Where><Gt><FieldRef Name="Created" Type="DateTime"/><Value Type="DateTime"><Today OffsetDays="-7" /></Value></Gt></Where></Query></View>'

Below is the full PoweShell Code. You can run the PowerShell script using Visual Studio code or Windows PowerShell ISE.

(Video) How to Retrieve all list names guids from SharePoint Online site using PowerShell

Try{Add-Type -Path 'E:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll'Add-Type -Path 'E:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'}catch {}$siteUrl = "https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"$username = "bijay@onlysharepoint2013.onmicrosoft.com"$password=ConvertTo-SecureString "******" -AsPlainText -Force$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)$ctx.Credentials = $credentials$Web = $ctx.Web$List = $web.get_lists().getByTitle("TrainingInformations")$Query = New-Object Microsoft.SharePoint.Client.CamlQuery;$caml = '<View><Query><Where><Gt><FieldRef Name="Created" Type="DateTime"/><Value Type="DateTime"><Today OffsetDays="-7" /></Value></Gt></Where></Query></View>'$Query.ViewXml =$caml$ListItems = $list.GetItems($Query);$ctx.Load($ListItems)$ctx.ExecuteQuery()$ListItems | ForEach-Object {write-host $_["Title"]}foreach ($item in $ListItems){$List.getItemById($item.id).deleteObject()}$ctx.ExecuteQuery()

Once you run the script, you can see the items created within last 7 days has been deleted like below:

Delete all items from a SharePoint Online list using PnP PowerShell - SPGuides (8)

Now we will see how we can delete items which are created before last 7 days using PowerShell in SharePoint online. In the above list, there is one item which is created before last 7 days.

Here we will slightly modify the CAML query and it should delete those items.

$caml = '<View><Query><Where><Lt><FieldRef Name="Created" Type="DateTime"/><Value Type="DateTime"><Today OffsetDays="-7" /></Value></Lt></Where></Query></View>'

Below is the full PowerShell script.

Try{Add-Type -Path 'E:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.dll'Add-Type -Path 'E:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\ISAPI\Microsoft.SharePoint.Client.Runtime.dll'}catch {}$siteUrl = "https://onlysharepoint2013.sharepoint.com/sites/Bhawana/"$username = "bijay@onlysharepoint2013.onmicrosoft.com"$password=ConvertTo-SecureString "*******" -AsPlainText -Force$ctx = New-Object Microsoft.SharePoint.Client.ClientContext($siteUrl)$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $password)$ctx.Credentials = $credentials$Web = $ctx.Web$List = $web.get_lists().getByTitle("TrainingInformations")$Query = New-Object Microsoft.SharePoint.Client.CamlQuery;$caml = '<View><Query><Where><Lt><FieldRef Name="Created" Type="DateTime"/><Value Type="DateTime"><Today OffsetDays="-7" /></Value></Lt></Where></Query></View>'$Query.ViewXml =$caml$ListItems = $list.GetItems($Query);$ctx.Load($ListItems)$ctx.ExecuteQuery()$ListItems | ForEach-Object {write-host $_["Title"]}foreach ($item in $ListItems){$List.getItemById($item.id).deleteObject()}$ctx.ExecuteQuery()

Once you run the above script, you can see the item will get deleted and see the output.

Delete all items from a SharePoint Online list using PnP PowerShell - SPGuides (9)

This is how to delete items created before N days from SharePoint online list using PowerShell.

You may like following PnP PowerShell tutorials:

  • Connect-PnPOnline : The ‘Connect-PnPOnline’ command was found in the module ‘SharePointPnPPowerShellOnline’
  • The term ‘Get-MsolUser’ is not recognized as the name of a cmdlet
  • Microsoft Lists – Create a List from Excel
  • SharePoint download multiple files + using PnP PowerShell

In this tutorial we learned how to Remove all items from a SharePoint Online list using PnP PowerShell and how to fix error Get-PnPListItem : The attempted operation is prohibited because it exceeds the list view threshold enforced by the administrator.

Delete all items from a SharePoint Online list using PnP PowerShell - SPGuides (10)

Bijay Kumar

(Video) PowerShell SharePoint Online - Disable versioning in document library + PnP PowerShell

I am Bijay from Odisha, India. Currently working in my own venture TSInfo Technologies in Bangalore, India. I am Microsoft Office Servers and Services (SharePoint) MVP (5 times). I works in SharePoint 2016/2013/2010, SharePoint Online Office 365 etc. Check out My MVP Profile.. I also run popular SharePoint web site EnjoySharePoint.com

FAQs

How do I delete all items from a SharePoint list in PowerShell? ›

ExecuteQuery() write-host "Total Number of List Items found:"$ListItems. Count #SharePoint Online PowerShell to 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].

How do I delete all items from a SharePoint list? ›

In your SharePoint site you can go to your list and You can click on the checkbox beside the first item on the list (It should highlight all of the items) and then click on "Items" in the List Tools ribbon and you will see a delete button.

How do I delete a SharePoint list in PowerShell? ›

Click on Site Settings gear >> Select Site contents from the menu. On the site contents page, Hover over the list that you want to delete and then click the drop-down menu icon (…) On the menu that appears, click on the “Remove” link and then confirm the prompt to send the list to the Recycle Bin.

How do you bulk delete list items using power automate flow? ›

Bulk Delete The SharePoint List Items Using Power Automate Flow
  1. Step 1 - Create an instant flow. We will create an instant flow which we will trigger manually.
  2. Step 2 - Initialize a variable. ...
  3. Step 3 - Add a Do until Loop. ...
  4. Step 4 - Add Get items action. ...
  5. Step 5 - Add Delete item action. ...
  6. Step 6 - Increment the variable.
Feb 10, 2022

How do I connect to PnP PowerShell? ›

Use Credentials from Windows Credentials Store to Connect to PnP Online:
  1. Open Control Panel >> Windows credential manager.
  2. Select Windows Credentials >> Click on “Add a new Generic credential”
  3. Enter your SharePoint Site URL, User Name and Password and hit save.
Feb 8, 2022

How do I delete a large list in SharePoint online? ›

Deleting a large SharePoint Online list. GUI: Microsoft improved SharePoint, so now it takes ~1 second to delete any SharePoint list, including 5000+ items list via GUI. PowerShell: “Remove-PnPList -Identity $list” command works very fast – ~1 second to delete entire list with >5000 items.

How do I delete all items in a list? ›

Remove all items from a Python list
  1. Using list. clear() function. list. ...
  2. Using Slice assignment. You can empty the list by replacing all the elements with an empty list. But simply doing a = [] won't clear the list. ...
  3. Using del statement. You can also use the del statement to delete the contents of an entire list.

How do you quickly delete items from a SharePoint list? ›

How to delete all items from SharePoint list Power Automate

How do I remove items from list? ›

Delete items from a list
  1. Open the list where you want to delete an item. If you can't find the list, select Site contents, and then open the list,
  2. Select the item or items.
  3. On the list's command bar, select Delete .
  4. When you are prompted to confirm, select OK.

How do I remove SharePoint online from PowerShell? ›

We can delete the site in two ways, where one is using SharePoint Online tenant and the other is using PowerShell command. Please open SharePoint admin centre-> Check the box for the site collection, which you wish to delete-> Click Delete in the ribbon.

How do I permanently delete SharePoint from PowerShell? ›

To delete a site collection permanently, first move the site collection to the Recycle Bin by using the Remove-SPOSite cmdlet and then delete it from the Recycle Bin by using the Remove-SPODeletedSite cmdlet.

What is get SPWeb? ›

The Get-SPWeb cmdlet returns all subsites that match the scope given by the Identity parameter. All subsites that meet the criteria are returned. The Identity can be either the full URL or a relative path.

How do you mass delete on SharePoint? ›

Depending on the version of SharePoint you're using, it may be quicker to delete single or multiple files using the right click menu.
  1. Open the document library where you want to delete files or folders.
  2. Select one or more files that you want to delete by hovering over the file and then clicking the check box.

How do I delete a list with power automate? ›

How to Delete a SharePoint List using Power Automate - YouTube

How do I remove items from power automate? ›

Power Automate delete all items in SharePoint list based on date
  1. Step 1: Create a Flow. To create a flow, Login to Power Automate and then click on Create and select Scheduled Cloud Flow.
  2. Step 2: Get items based on date column. ...
  3. Step 3: Delete items. ...
  4. Step 4: Run the Flow.
Feb 5, 2022

How do I use SharePoint Online PnP PowerShell? ›

PowerShell module.
  1. Step 1: Uninstall the Legacy SharePointPnPPowerShellOnline Module. Uninstall Any previous PnP PowerShell Modules for SharePoint Online installed. ...
  2. Step 2: Install the New PnP PowerShell Module. ...
  3. Step 3: Register a new Azure AD Application and Grant Access to the tenant.
Feb 26, 2022

What is the difference between PnP and PowerShell? ›

PnP PowerShell Cmdlets works in the context of the current user, where as SPO command runs with the Tenant Admin rights. PnP PowerShell Cmdlets connects to the SiteCollection level, where as SPO has the commands to target Tenant level.

What is PnP in PowerShell? ›

PnP PowerShell is a . NET Core 3.1 / . NET Framework 4.6. 1 based PowerShell Module providing over 600 cmdlets that work with Microsoft 365 environments such as SharePoint Online, Microsoft Teams, Microsoft Project, Security & Compliance, Azure Active Directory, and more.

How do I truncate a SharePoint list? ›

Run the . \Truncate-SPList command inside SharePoint Management Powershell. Enter the URL and Name of the list ( or pass in parameters for -SiteURL and -ListName. Confirm that you want to remove all items from the list ( 'y' )

Why can't a SharePoint list delete? ›

If any kind of retention policy is turned on your sites you can't delete folders and lists the have content in them until you delete all the items in the list first so copies of the content move over to the item retention library.

How do I get more than 5000 items from a SharePoint list? ›

How to fix the SharePoint 5000 Item Limit Threshold
  1. Bring Down the Number of Items to Less Than 5,000. The first fix you can do is to bring the number of items that you have to less than the item viewing threshold. ...
  2. Reorganize Your Whole Library. ...
  3. Create Metadata Properties.
Mar 22, 2021

What is get SPWeb? ›

The Get-SPWeb cmdlet returns all subsites that match the scope given by the Identity parameter. All subsites that meet the criteria are returned. The Identity can be either the full URL or a relative path.

Videos

1. How to delete, restore and permanently delete SharePoint Online site using PowerShell
(EnjoySharePoint)
2. Sharepoint: How to delete rows from a SharePoint list using PnP PowerShell? (3 Solutions!!)
(Roel Van de Paar)
3. Download multiple files in SharePoint | Download multiple files from sharepoint using powershell
(EnjoySharePoint)
4. Enable SharePoint Online Site Collection App Catalog using PowerShell and PnP PowerShell
(EnjoySharePoint)
5. SharePoint Online storage limits + Set Storage Quota using PowerShell in SharePoint Online
(EnjoySharePoint)
6. Create SharePoint site column using PowerShell | Create site column in SharePoint Online PowerShell
(EnjoySharePoint)

Top Articles

You might also like

Latest Posts

Article information

Author: Rueben Jacobs

Last Updated: 12/09/2022

Views: 6057

Rating: 4.7 / 5 (77 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Rueben Jacobs

Birthday: 1999-03-14

Address: 951 Caterina Walk, Schambergerside, CA 67667-0896

Phone: +6881806848632

Job: Internal Education Planner

Hobby: Candle making, Cabaret, Poi, Gambling, Rock climbing, Wood carving, Computer programming

Introduction: My name is Rueben Jacobs, I am a cooperative, beautiful, kind, comfortable, glamorous, open, magnificent person who loves writing and wants to share my knowledge and understanding with you.