Forum Discussion

IanTaylor2050's avatar
IanTaylor2050
Copper Contributor
May 13, 2023

Add item to SharePoint online list if item not exist, else update - PNP powershell

I am using PNP PowerShell script to add items to SharePoint list if items doesn't exist. If items exist, just update those items. Below is the script, however the script just keeps on inserting even when the item already exist.

 

Any idea where I am going wrong? Below is the powershell script and sharepoint list

 

Connect-PnPOnline -Url $SiteURL
$items = Get-PnPListItem -List $ListName -Query "<View><Query><Where><Eq><FieldRef Name='Title'/><Value Type='Text'>Corporate Governance Policy</Value></Eq></Where></Query></View>"
$items.Count
write-host  $items.Count

if($items.Count -gt 0) # one or more items exist
{
	write-host  "Item exist" $items.Count $itemArray[0];
  foreach($item in $items) #update each item that already exists
  {
    Set-PnPListItem -List $ListName -Identity $item.Id  -Values @{"Title" = $itemArray[0];"LabelName" =$itemArray[1]}   
  }

}
else #add an item if not already exists
{
	write-host  "Item does not exist" $items.Count $itemArray[0];
  Add-PnPListItem -List $ListName -Values @{"Title" = $itemArray[0];"LabelName" =$itemArray[1]}

}	

  

1 Reply

  • NikolinoDE's avatar
    NikolinoDE
    Platinum Contributor

    IanTaylor2050 

    The issue in your PowerShell script seems to be related to the variable $itemArray. It is not clear where you are populating this variable with the values you want to add or update in the SharePoint list.

    To add or update items in a SharePoint Online list based on their existence, you can modify your script as follows:

    Connect-PnPOnline -Url $SiteURL
    
    # Define the values to add or update
    $title = "Corporate Governance Policy"
    $labelName = "YourLabelName"
    
    # Check if the item exists
    $item = Get-PnPListItem -List $ListName -Filter "Title eq '$title'"
    if ($item) {
        Write-Host "Item exists: $($item.Id)"
        # Update the existing item
        Set-PnPListItem -List $ListName -Identity $item.Id -Values @{"Title" = $title; "LabelName" = $labelName}
    }
    else {
        Write-Host "Item does not exist"
        # Add a new item
        Add-PnPListItem -List $ListName -Values @{"Title" = $title; "LabelName" = $labelName}
    }

    In this modified script, you define the values ($title and $labelName) that you want to add or update in the SharePoint list. The script then checks if an item with the specified title already exists in the list. If it does, it updates the item with the new values. If the item doesn't exist, it adds a new item with the specified values.

    Make sure to replace $SiteURL with the URL of your SharePoint site and $ListName with the name or ID of your target list.

    Please ensure that you have the necessary permissions to add or update items in the SharePoint list.

    *This post was created with the help of AI.

Resources