I am creating a LIST in SharePoint using PowerShell via a CSV file. I am able to create the list as well as add items successfully, although I need to validate that the item (row) that I add to the list does not already exist in the list, prior to updating the list.
In the code I am not able to get $ItemExist correctly. It always returns a Null value. ($MaxItems currently has a value of 2 as there are 2 items in the list "list_DLs").
(I have already checked all other posts on the site for the same issue and did not find a fix)
$cred = new-object -typename System.Management.Automation.PSCredential -argumentlist $AdminName, $Pass
$Path_SpFiles = "C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\16\ISAPI"
Add-Type -path "$Path_SpFiles\Microsoft.SharePoint.Client.Runtime.dll"
Add-Type -path "$Path_SpFiles\Microsoft.SharePoint.Client.dll"
# ------- Connect to SharePoint Site and fetch List Items ----------------
[Net.ServicePointManager]::SecurityProtocol = 'TLS11','TLS12','ssl3'
$site = "https://xyz.sharepoint.com/sites/mco"
$context = New-Object Microsoft.SharePoint.Client.ClientContext($site)
$credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($AdminName, $Pass)
$context.Credentials = $credentials
$ListName="list_DLs"
$list = $context.Web.Lists.GetByTitle($ListName)
$query = [Microsoft.SharePoint.Client.CamlQuery]::CreateAllItemsQuery(5000)
$items = $list.GetItems($query)
$context.Load($items)
$context.ExecuteQuery()
$MaxItems = $items.count
$SourceFile = "C:\Temp\list_DLs.csv"
$CSVData = Import-CSV -path $SourceFile
foreach ($row in $CSVData)
{
#----------------------------------------------
#Check if the item has previously been added
if ($MaxItems -ne 0)
{
$ItemExist = $items | where{$_.Title -eq $row.PrimarySmtpAddress}
if($ItemExist -ne $null) {Continue}
}
#----------------------------------------------
$ListItemInfo = New-Object Microsoft.SharePoint.Client.ListItemCreationInformation
$Item = $list.AddItem($ListItemInfo)
$Item["Title"] = $row.PrimarySmtpAddress
$Item.Update()
$Context.ExecuteQuery()
Break
}
I know that the $items in being returned correctly, because if I run this snippet of code to iterate through the items I am able to see them correctly. I am just not able to get $ItemExist to work correctly
ForEach ($item in $items)
{
$b = $item["Title"]
$b
Break
}
CodePudding user response:
You can use a CAML query to check if the item is already in the list.
CAML query:
$caml="
<View>
<Query>
<Where><Eq><FieldRef Name='Title' /><Value Type='Text'>1</Value></Eq></Where>
</Query>
</View>
"
$ItemExist = Get-PnPListItem -List $targetList -Query $caml