SharePoint Online: Add New List Item using PowerShell

Requirement: When working with SharePoint Online, I had a requirement to add new list items to a list from the PowerShell script. This blog post will cover how to create a list item in SharePoint Online using PowerShell, with some examples.

Introduction

SharePoint lists are used to store and manage data in SharePoint sites. At times, administrators need to add list items programmatically instead of manually. PowerShell provides an easy way to automate this task using the CSOM method and Add-PnPListItem cmdlet. In this beginner’s guide, we will go through a step-by-step process to add SharePoint list items using PowerShell.

How to add an item to a List in SharePoint Online?

Adding items to SharePoint lists is a common task that you will likely find yourself doing regularly. Here’s a quick overview of how to do it:

  1. Log in to your SharePoint site and navigate to the list that you want to add an item to.
  2. Click on the “+ New” link from the command bar.
  3. Enter the information for the new item in the appropriate fields.
  4. Click the “Save” button.Add item to SharePoint Online list

And that’s all there is to it! Let’s see how to add items to the SharePoint Online list using PowerShell.

SharePoint Online: PowerShell to Add a List Item

There are many situations where you may want to create a list item in SharePoint Online without going through the web-based user interface in your SharePoint Online. Luckily, we have an easy way to do this using PowerShell. In this blog post, we will show you how to add an item to a SharePoint Online list using PowerShell.

To add a list item using PowerShell, we’ve to set the value for each custom column in the list. Here is the SharePoint Online PowerShell to create a list item:

#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"

#Set Config Parameters
$SiteURL="https://Crescent.sharepoint.com"
$ListName="Tasks"

Try { 
    #Get Credentials to connect
    $Cred= Get-Credential
 
    #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 List
    $List=$Ctx.Web.Lists.GetByTitle($ListName)
 
    #sharepoint online powershell add list item
    $ListItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation  
    $ListItem = $List.AddItem($ListItemInfo)
    
    #Set Column Values
    $ListItem["Title"] = "Project Darwin"

    #Set People Picker Field value
    $AssignedToUser = $Ctx.web.EnsureUser("Salaudeen@TheCrescentTech.com")
    $ListItem["AssignedTo"] = $AssignedToUser
    
    #Set Date Fields
    $ListItem["StartDate"] = "01/07/2015"
    $ListItem["DueDate"] = "01/08/2015"
    
    #Set Percentage Field 
    $ListItem["PercentComplete"] = "0.2" #20%

    #add item to sharepoint online list powershell
    $ListItem.Update()
    $Ctx.ExecuteQuery()
 
    Write-host -f Green "New Item has been added to the List!"
}
Catch {
    write-host -f Red "Error:" $_.Exception.Message
}  

This inserts a new item into the Tasks list. This is a quick and easy way to add an item to the list in SharePoint Online using PowerShell, without having to use the web browser user interface. Here is the result:

sharepoint online powershell add item to list

PowerShell to Create List Items in SharePoint Online

Let’s add some error handling code and get the credentials at run time in the script. Here is the SharePoint Online PowerShell CSOM to add list items:

#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"

#Config Parameters
$SiteURL="https://crescent.sharepoint.com"
$ListName="Random"
$ItemsToCreate="1000"

Try {
    $Cred= Get-Credential
    $Credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($Cred.Username, $Cred.Password)

    #Setup the context
    $Ctx = New-Object Microsoft.SharePoint.Client.ClientContext($SiteURL)
    $Ctx.Credentials = $Credentials
        
    #Get the List
    $List = $Ctx.Web.Lists.GetByTitle($ListName)
    $Ctx.Load($List)
    $Ctx.ExecuteQuery()

    #add an item to list SharePoint Online PowerShell - with Random Data
    For($i=1; $i -le $ItemsToCreate; $i++)
    {
        #create list item in sharepoint online using powershell
        $ListItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
        $ListItem = $List.AddItem($ListItemInfo)
        $ListItem["Title"] = $I
        $ListItem.Update()
        $Ctx.ExecuteQuery()

        Write-host "New Item $I Added to the List!" -ForegroundColor Green  
    }
}
Catch {
    write-host -f Red "Error Adding Items to List!" $_.Exception.Message
}

This script randomly creates list items in bulk.

PnP PowerShell to Add List Item in SharePoint Online

When working with SharePoint Online, you may need to programmatically add an item to a list. Fortunately, there is an easy way to accomplish this using PowerShell. You can use a PowerShell script to help automate creating content that needs to be added on a regular basis or unattended.

Here is the general syntax of the Add-PnPListitem cmdlet:

Add-PnPListItem 
[-List <ListPipeBind>] 
-Values <Hashtable> 
[-ContentType <ContentType>]
[-Folder <FolderPipeBind>]
[-Label <String>]
[-Connection <PnPConnection>] 

The crucial thing is the -Values hashtable that adds the metadata for each list item by mapping column names of the list to respective values. Here is how to add an item to the list in SharePoint Online with the PnP PowerShell cmdlet Add-PnPListItem.

  1. The first step is to connect to your SharePoint Online site URL. You can do this by running the following cmdlet: Connect-PnPOnline.
  2. Once you are connected, you can use the Add-PnPListItem cmdlet to add items to your list. For example, the following command will add a new item to a list with the field Internal name and the value for the field: Add-PnPlistItem -list “List Name” -values @{“Field Internal Name”=”Field Value”; “Field Internal Name”=”Field Value”}

To create a list item in SharePoint through PowerShell, use this syntax:

Add-PnPListItem -List "YourListName" -Values @{"Field1InternalName"="Value1"; "Field2InternalName"="Value2"}

Here is an example of adding a single value to a SharePoint List:

#Config Variables
$SiteURL = "https://Crescent.sharepoint.com"
$ListName ="Projects"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Interactive

#Add List Item - Internal Names of the columns: Value
Add-PnPListItem -List $ListName -Values @{"Title" = "SharePoint 2016 Migration V2"; "ProjectID"="Abj-IT-3025"}

Use the internal names of the fields when supplying field names. You can also specify the “ContentType” parameter with name or ID if you would like to add an item of a specific content type. Once you execute this PowerShell script, a new item will be added to the list. Adding items to SharePoint Online lists using PowerShell is a quick and easy way to populate your data. You can also use the Hashtables to make the script more readable:

$ItemValues = @{
  "Title" = "Website Design Project"
  "DueDate" = (Get-Date).AddDays(7) # Due in 7 days
}

Add-PnPListItem -List "Project Tasks" -Values $ItemValues

Adding list items with different column types

Here is a quick table that shows PowerShell examples to add list items to the SharePoint Online list with different column types:

Column TypePowerShell Example
Date and TimeAdd-PnPListItem -List "Tasks" -Values @{"DueDate"="10/23/2022"}
LookupAdd-PnPListItem -List "Tasks" -Values @{"ProjectLookupId"=5}
Multivalue LookupAdd-PnPListItem -List "Tasks" -Values @{"ProjectLookupId"="5,6"}
Yes/NoAdd-PnPListItem -List "Tasks" -Values @{"Completed"=$true}
Person or GroupAdd-PnPListItem -List "Tasks" -Values @{"AssignedToId"=10}
ChoiceAdd-PnPListItem -List "Tasks" -Values @{"Status"="In Progress"}
Multi-value ChoiceAdd-PnPListItem -List "Tasks" -Values @{"Tags"="Tag1,Tag2"}
NumberAdd-PnPListItem -List "Tasks" -Values @{"Quantity"=100}
Single Line of TextAdd-PnPListItem -List "Tasks" -Values @{"Title"="New Task"}
Multiline TextAdd-PnPListItem -List "Tasks" -Values @{"Description"="This is a detailed description of the task."}

Here,

  • Lookup: For Lookup value, You need to provide the ID of the item in the lookup list. In the example, 5 represents the ID of the item you want to reference.
  • Multivalue Lookup: Similar to a single lookup, you can specify multiple IDs as an array, separated by a comma. This is for fields that allow multiple lookup values.
  • Yes/No: Boolean values ($true or $false) are used to represent Yes/No fields.
  • Person or Group: You need the ID of the user or group from the site’s user information list. In this example, 10 represents the ID of the user.
  • Multi-value Choice: For fields that allow selecting multiple choices, provide the choices separated by commas.

The above scripts work just fine with simple field types such as single lines of text, choice, Yes/No, etc. However, we have to handle them differently for other field types such as Managed metadata, Hyperlink, Lookup, People Picker, etc. Here are my posts to help:

Bulk Add List items using PnP PowerShell

The New-PnPBatch method is a part of the new PnP PowerShell module, which is widely used for automating tasks in SharePoint Online. This method allows for batching requests together, significantly improving performance by reducing the number of round trips to the server when performing bulk operations. Let’s look at an example of inserting list items into a list by fetching the values from a CSV file.

The below PowerShell imports multiple items from a CSV file to a SharePoint list named “Parent Projects” with at least two columns: “Title” and “Department”.

#Parameters
$SiteURL = "https://crescent.sharepoint.com/sites/pmo"
$ListName = "Parent Projects"
$CSVFile = "C:\Temp\Parent Projects.csv"

#Connect to SharePoint Online Admin Center
Connect-PnPOnline -URL $SiteURL -Interactive

# Read CSV file
$CSVData = Import-CSV $CSVFile -Header Title, Department

#Create a New Batch
$Batch = New-PnPBatch

#Loop through each row in the CSV file
ForEach($item in $CSVData)
{
    Add-PnPListItem -List $ListName -Values @{"Title" = $Item.Title;  "Department" = $Item.Department } -Batch $Batch
}

# Execute the batch all at once
Invoke-PnPBatch -Batch $Batch

Conclusion

The PowerShell way of adding list items empowers you to automate repetitive tasks, improve data accuracy, and save valuable time. The Add-PnPListItem cmdlet offers a programmatic way to insert SharePoint list items through PowerShell scripting. This is useful for bulk-adding items from external data sources, automating repetitive tasks, and simplifying administration.

In this article, we explored the basics of adding SharePoint list items through PowerShell, Add-PnPListItem cmdlet, and practical examples of adding items into SharePoint lists. You can easily extend these samples to build custom solutions for your specific requirements.

How do I add Multiple List items in Batch in SharePoint Online?

You can perform bulk operations such as delete or add items to a SharePoint Online list in batches faster using the New-PnPBatch cmdlet in PnP PowerShell.
More info: How to Add Multiple List Items in Batch using PowerShell?

How do I import data from CSV into a SharePoint Online list?

Although you can create a list from a CSV file or Excel, successive imports can be achieved with Import-CSV and Add-PnPList item cmdlets in PowerShell.
More info: Import CSV to SharePoint online list PowerShell

How do I upload a file to SharePoint Online PowerShell?

To upload a file to the SharePoint document library using PowerShell, use Files.Add method in CSOM or Add-PnPFile cmdlet from PnP PowerShell.
More info: Upload files to SharePoint Online using PowerShell

How do I get items from a SharePoint Online list in PowerShell?

Use the “List.GetItems” method or Get-PnPListItem from PnP PowerShell to query and get list items from SharePoint Online.
More info: SharePoint Online Get list items PowerShell

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two-decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. He has held various positions including SharePoint Architect, Administrator, Developer and consultant, has helped many organizations to implement and optimize SharePoint solutions. Known for his deep technical expertise, He's passionate about sharing the knowledge and insights to help others, through the real-world articles!

Leave a Reply

Your email address will not be published. Required fields are marked *