Forum Discussion
AHun78
Oct 02, 2023Copper Contributor
PnP PowerShell Check if items exists in List
Hi All, I have the following script that checks to see if a Site exists in a SPO list and either updates or adds the item to the list. For some reason it never updates the list items... It ju...
AHun78
Oct 03, 2023Copper Contributor
Thanks for the reply... 🙂
I tried doing that but it doesn't resolve the issue... The item always get's created as a new item rather than updating existing item
# Connect to Microsoft 365
Connect-PnPOnline -Url "https://<tenant>.sharepoint.com" -Interactive
# Get all sites
$sites = Get-PnPTenantSite -Template "GROUP#0"
$SiteDirectoryURL = “https://<tenant>.sharepoint.com/sites/SPOSiteProvisioning”
Connect-PnPOnline -Url $SiteDirectoryURL -Interactive
$ListName = “Site Directory” # Site Directory list name
foreach ($site in $sites) {
# Connect to the site
$siteConnect = Connect-PnPOnline -Url $site.Url -Interactive -ReturnConnection
# Get the root web with "created" property
$Web = Get-PnPWeb -Includes Created -Connection $siteConnect
# Get site details
if ($site.Template -like "GROUP*") {
# Get Group Owners
$GroupOwners = (Get-PnPMicrosoft365GroupOwners -Identity $site.GroupId.Guid -Connection $siteConnect | Select-Object -ExpandProperty Email) -join "; "
} else {
$GroupOwners = $site.Owner
}
# Prepare item values
$itemValue = @{
"GUID" = $site.GroupId;
"Title" = $site.Title;
"URL" = $site.Url;
"SiteDescription" = $site.Description;
"SiteTemplate" = $site.Template;
"SiteOwner" = $GroupOwners;
"PrivacySetting" = $site.Visibility; # Privacy setting
"ExternalSharing" = $site.SharingCapability; # External sharing capability
"CreatedOn" = $web.Created.ToString("dd/MM/yyyy HH:mm:ss") # Site creation date
}
# Check if an item with the same URL exists in the list
$listItem = Get-PnPListItem -List $ListName -Query "<View><Query><Where><Eq><FieldRef Name='URL' /><Value Type='Text'>${site.Url}</Value></Eq></Where></Query></View>"
# If the item exists, update the other fields
if ($listItem) {
Set-PnPListItem -List $ListName -Identity $listItem -Values $itemValue
Write-Host "Updated item with title: $($itemValue.Title)" -ForegroundColor Yellow
}
# If the item does not exist, create a new item
else {
Add-PnPListItem -List $ListName -Values $itemValue
Write-Host "Created new item with title: $($itemValue.Title)" -ForegroundColor Green
}
}
Oct 03, 2023
What value to do you get one $listItem?
Because it sounds like it's not matching at all, so that's why. Is the URL field a Single line of text field or URL field?
Because it sounds like it's not matching at all, so that's why. Is the URL field a Single line of text field or URL field?