SharePoint Online: Update List Items using PowerShell

Requirement: SharePoint Online PowerShell to Edit and update List Items.

How to update List Items in SharePoint Online using PowerShell?

If you want to update a list item in SharePoint Online, but don’t want to go through the web user interface every time – as updates happen frequently, and are time-consuming – There is a way to automate this process with PowerShell. PowerShell provides a powerful way to automate updates to SharePoint lists. With a few PowerShell commands, you can connect to SharePoint Online and rapidly update list items in bulk. This blog post will show you how to update a list item in SharePoint Online using PowerShell.

To update a SharePoint list using PowerShell, here are the steps:

  1. Connect to SharePoint Online from PowerShell
  2. Get SharePoint List items to update
  3. Update the list item(s).

Update List Items in SharePoint Online using PowerShell CSOM Script

Sometimes there is a need to update the list items in bulk to modify data or status. Although the SharePoint UI allows editing list items, bulk updates can be challenging. This is where SharePoint Client Side Object Model (CSOM) combined with PowerShell’s scripting capabilities can help. We can write PowerShell scripts to connect to SharePoint Online, fetch list data and rapidly update multiple items simultaneously.

Here is the example for SharePoint Online PowerShell script to update 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"
  
#Variables for Processing
$SiteUrl = "https://crescent.sharepoint.com/"
$ListName="Projects"

$UserName="admin@crescent.com"
$Password ="Password goes here"
 
#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

try{ 
  
    #Filter and Get the List Items using CAML
    $List = $Context.web.Lists.GetByTitle($ListName)

    #Get List Item by ID
    $ListItem = $List.GetItemById(1)  

    #Update List Item title
    $ListItem["Title"] = "Project Darwin"  
    $ListItem.Update()  

    $Context.ExecuteQuery()
    write-host "Item Updated!"  -foregroundcolor Green  
}
catch{  
    write-host "$($_.Exception.Message)" -foregroundcolor red  
} 

This updates the Item with ID: 1 for the given list. You can also use $ListItem.SystemUpdate() method to preserve metadata like the last modified and keep versions intact. Instead of CSOM DLLs, You can also reference the SharePoint Online Management Shell (Import-Module Microsoft.Online.SharePoint.Powershell).

sharepoint online powershell update list item

The above script updates a particular list item. What if you want to update all items on the list?

PowerShell to Update All List Items in SharePoint Online:

List items in SharePoint Online can be updated using PowerShell. This can be done by retrieving the list items and then updating their properties. Here is the PowerShell to update list items in SharePoint Online:

#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
$SiteURL="https://crescent.sharepoint.com"
$ListName="Projects"

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
    $Web = $Ctx.web

    #Get the List    
    $List = $Ctx.Web.Lists.GetByTitle($ListName)
    $Ctx.Load($List)
    $Ctx.ExecuteQuery()

    #Get All List items
    $ListItemsCAML = New-Object Microsoft.SharePoint.Client.CamlQuery
    $ListItemsCAML.ViewXml = "<View Scope='RecursiveAll'></View>"
    $ListItems = $List.GetItems($ListItemsCAML)
    $Ctx.Load($ListItems)
    $Ctx.ExecuteQuery()

    Write-host "Total Items Found:"$List.ItemCount

    #Iterate through each item in ForEach loop and update
    Foreach ($ListItem in $ListItems)
    {
        #Set New value for List column
        $ListItem["Reference"] = $ListItem["ID"]
        $ListItem.Update()
        $Ctx.ExecuteQuery() 
    }
    
    Write-host "All Items in the List: $ListName Updated Successfully!" -ForegroundColor Green  
}
Catch {
    write-host -f Red "Error Updating List Items!" $_.Exception.Message
}

Using CSOM and PowerShell, you can now rapidly automate updates to large SharePoint lists without any custom code. We first connected to the SharePoint Online site with valid user credentials. Next, we retrieved the target list items to update. Finally, we updated the desired columns like Title and Status for the selected item.

SharePoint Online: PnP PowerShell to Update List Item

PowerShell is a powerful scripting language that can be used to automate various tasks, including updates to SharePoint list items. In order to update a list item, you must first connect to your SharePoint site using PowerShell. Once you are connected, you can use the Get-PnPListItem cmdlet to retrieve the list item you wish to update. To update the item, simply use the Set-PnPListItem cmdlet, specifying the ID of the list item and the new values for the fields you wish to update. This cmdlet will automatically save your changes back to SharePoint.

Here is how to update list items using PnP PowerShell in SharePoint Online using the Set-PnPListItem cmdlet.

#Config Variables
$SiteURL = "https://crescent.sharepoint.com"
$ListName ="Projects"
$ListItemID ="10"

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get List Item to Update
$ListItem = Get-PnPListItem -List $ListName -Id $ListItemID -ErrorAction Stop

#Update List Item - Internal Names of the fields : Value
Set-PnPListItem -List $ListName -Identity $ListItem -Values @{"ProjectName" = "SharePoint 2016 Migration"; "ProjectID"="Abj-IT-3021"}

Similarly, we can use the query parameter to filter and get a list item using CAML Query:

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

#Connect to PnP Online
Connect-PnPOnline -Url $SiteURL -Credentials (Get-Credential)

#Get List Item to Update by Query
$ListItem = Get-PnPListItem -List $ListName -Query "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>$ListItemTitle</Value></Eq></Where></Query></View>" -PageSize 1 -ErrorAction Stop

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

If you want to bulk update list items from a CSV file, use: SharePoint Online: Update List Items from a CSV File using PowerShell

The above scripts work just fine with simple field types like 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:

Wrapping up

Updating SharePoint lists efficiently is essential for keeping data in sync across teams. PowerShell provides a simple way to automate updates to SharePoint Online lists. In this guide, you learned how to connect to SharePoint Online, retrieve a list and update list items using CSOM PowerShell script and PnP PowerShell cmdlet Set-PnPListItem. With these PowerShell skills, you can rapidly update list data like contacts, issues, announcements and more.

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!

16 thoughts on “SharePoint Online: Update List Items using PowerShell

  • @Salaudeen Rajack,
    Thank you for all your wonderful work by sharing all the amazing scripts.
    ————————————————
    A question, regarding updating the SharePoint Online list items;
    -I have a script that pulls all site owners and exports them to a CSV on the local server. I have now created a SharePoint online list off the CSV export, and have all the associated site owners, associated site names, and URLs in the list.

    What I want to do is;
    1) update the list without using the csv saved locally, I want the script to first delete all the list items on the fly(I’ve done that bit). Probably, there is an option to overwrite the listitems without emptying the list.
    2) Modify the script to read from a variable, then add the items to the corresponding list’s columns.
    In summary, below is the line that exports my results, but I want to write the results directly to the SharePoint list, rather than a local CSV.
    —————————-
    #Export Site Owners report to CSV
    $SiteOwners | Export-Csv -path $CSVPath -NoTypeInformation
    ——————————-
    I hope my question makes sense.

    Thank you all in advance for your help.

    Reply
    • Has anyone of you guys tried using my scenario? I’m still unable to find a fix
      Thanks

      Reply
        • Hi Salaudeen,
          Thank you for getting back to me.
          I wanted to avoid uploading from a CSV(the script is still saving to a CSV as well), just in case the local server goes down when the script is running.
          The reason is that we are going to automate this script via an Azure AD runbook and connect it to a power app, that the Help Desk guys can use to look up the various site owners.

          ————————-:Update:—————————————-
          I sat down with my teammates and managed to get the list to give us what need.
          We used one of your scripts to add that line that writes directly to the list.
          https://www.sharepointdiary.com/2018/02/get-sharepoint-online-site-owner-using-powershell.html#ixzz849XaAs1P
          ————————————
          $AddListItems = Add-PnPListItem -List “AllSiteOwners” -Values @{“field_2” = $Site.Title; “Title”= $Site.Url; “field_0” = $GroupOwners}.
          ————————————–
          Some bits are not working, but we are working to improve the script and any more tweaks are welcome. I’m looking to throw in an option to get the site creation date into the list.
          ——————————–Script is below, site names are fiction—————-
          #Step One——————————————————-
          #First step is to empty the list in SharePoint Online.

          #Config Variables
          $AdminCenterURL = “https://contoso-admin.sharepoint.com”
          $CSVPath = “C:\Temp\InventorySiteOwners.csv”
          #$Credential = Get-Credential #Gets the user credentials, and then stores them in the $Credential variable.

          #Variable for the SharePoint list
          $SiteURL = “https://contosocloud.sharepoint.com/sites/DEMO”
          $ListName = “AllSiteOwners”

          #Connect-SPOService -url $AdminCenterURL -Credential $Cred
          Connect-SPOService -url $AdminCenterURL -credential contoso@admin.com
          Connect-AzureAD

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

          #Get List Items to Delete
          $ListItems = Get-PnPListItem -List $ListName -PageSize 500

          #Create a New Batch
          $Batch = New-PnPBatch
          #Clear All Items in the List
          Write-Host “Deleting list items in” $listName -ForegroundColor Magenta
          ForEach($Item in $ListItems)
          {
          Write-Host “Deleting” $item.Id -ForegroundColor Green
          Remove-PnPListItem -List $ListName -Identity $Item.ID -Recycle -Batch $Batch | Out-Null #Out-Null will wait for the whole command to execute
          }

          #Send Batch to the server
          Invoke-PnPBatch -Batch $Batch

          #Step Two———————————————
          #Get all Site Collections
          $Sites = Get-SPOSite -Limit ALL
          $SiteOwners = @() #an empty array is assigned into a variable called $SiteOwners

          #Get Site Owners for each site collection
          $Sites | ForEach-Object {
          If($_.Template -like ‘GROUP*’)
          {
          $Site = Get-SPOSite -Identity $_.URL
          $Site.Url

          #Get Group Owners
          $GroupOwners = (Get-AzureADGroupOwner -ObjectId $Site.GroupID | Select -ExpandProperty UserPrincipalName) -join “; ”
          }
          Else
          {
          $GroupOwners = $_.Owner
          }

          #Collect Data
          $SiteOwners += New-Object PSObject -Property ([Ordered]@{
          ‘Site Title’ = $_.Title
          ‘URL’ = $_.Url
          ‘Owner(s)’ = $GroupOwners

          })

          #Adding the items directly to the SharePoint List
          #$AddListItems = Add-PnPListItem -List “AllSiteOwners” -Values @{“field_2” = “$_.Title”; “Title” = “$_.Url”; “field_0” = “$GroupOwners”} #Not working-Try 1
          $AddListItems = Add-PnPListItem -List “AllSiteOwners” -Values @{“field_2” = $Site.Title; “Title”= $Site.Url; “field_0” = $GroupOwners} #Working -Try 2
          }
          #Get Site Owners
          $SiteOwners
          #Export Site Owners report to CSV
          $SiteOwners | Export-Csv -path $CSVPath -NoTypeInformation

          #Get Script execution time

          Reply
        • Update 2.
          The script is for some unknown reasons duplicating some items in the SharePoint online list. I have set the column to Enforce unique values as a workaround. The error thrown is below.
          —————————————————————-
          “Add-PnPListItem : The list item could not be added or updated because duplicate values were found in the following field(s) in the list: [SiteName].
          At line:40 char:17
          + … ListItems = Add-PnPListItem -List “AllSiteOwners” -Values @{“field_2″ …
          + ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
          + CategoryInfo : InvalidOperation: (:) [Add-PnPListItem], PSInvalidOperationException
          + FullyQualifiedErrorId : InvalidOperation,PnP.PowerShell.Commands.Lists.AddListItem”
          ———————————————————————–
          Note:
          The exported CSV file has no duplicates at all!

          Reply
  • I have been trying to access/manipulate a SharePoint Online list through PowerShell, and while I can connect to the site, and populate $ctx, it’s failing on $Ctx.Web.Lists. The error I’m getting is “An error occurred while enumerating through a collection: The collection has not been initialized…”

    Any thoughts?

    Reply
  • Hi,
    I want to update file meta data without changing mobified by / modified date in CSOM using powershell. Can anyone please help me??

    Reply
  • Hi Salaudeen – I have a script that adds a an item list and it works. Are you able to help me attach an attachment when I create a new item?

    I have a list item that will always contain an attachment and would like to create a list item and attach a file at the same time. Any idea how I can incorporate attaching a file in my script?

    Reply
  • How i can delete one Item ?

    Reply
  • can you show an example where you update the SP list if the ID in the csv is equal to the ID on the SP list?

    Reply
      • #Config Variables
        $SiteURL = “https://xxxxxxx.sharepoint.com/sites/test”
        $ListName =”test_powershell”
        $data_file = Import-Csv -Path “D:\csv\test_powershell.csv” -Delimiter “,”

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

        #Get List Item to Update
        $ListItems = Get-PnPListItem -List $ListName
        foreach($file in $data_file)
        {
        foreach($ListItem in $ListItems)
        {
        $serverURL = $ListItem[“siteurl”]
        if($serverURL -eq $($file.Url))
        {
        $itemID = $ListItem[“ID”]
        $itemDes = $ListItem[“comments”]
        if($itemDes)
        {
        Write-Host “Comments available”-f Green

        #Get List Item to Update
        $ListItemID = Get-PnPListItem -List $ListName -Id $itemID -ErrorAction Stop

        #Write-Host $ListItemID[“comments”] -f Green
        #Write-Host “”
        $itemDes = $itemDes + “;” + $file.Description

        Set-PnPListItem -List $ListName -Identity $ListItemID -Values @{“comments” = $itemDes}
        #-Values @{“ProjectName” = “SharePoint 2016 Migration”; “ProjectID”=”Abj-IT-3021”}
        $itemDes = $null
        }
        else
        {
        Write-Host “Nocomments ” -f Red
        #Get List Item to Update
        $ListItem = Get-PnPListItem -List $ListName -Id $itemID -ErrorAction Stop

        $itemDes =$file.Description
        Set-PnPListItem -List $ListName -Identity $ListItem -Values @{“comments” = $itemDes}
        $itemDes = $null

        #-Values @{“ProjectName” = “SharePoint 2016 Migration”; “ProjectID”=”Abj-IT-3021”}
        }
        }
        }
        }

        Reply

Leave a Reply

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