Forum Discussion
Add item to SharePoint online list if item not exist, else update - PNP powershell
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.