I am using the powershell script shared below.
However, I am encountering a 401 Unauthorized error when executing Get-PnPList command.
This error is causing the script to stop rather execution.
Error: Get-PnPList cmd is not connect, showing the (401) Unauthorized error and then script is stopped without excuting the other below code.
please give the solution to solving this query, it will be very helpful to us.
Connect to the SharePoint site using Client ID and Client Secret
$siteUrl = "https://.sharepoint.com/sites"
$clientId = "................................."
$clientSecret = "...................................."
Authenticate with SharePoint Online
Connect-PnPOnline -Url $siteUrl -ClientId $clientId -ClientSecret $clientSecret
SharePoint List and Field Names
$listName = "BlueCurrent_10_items"
$addressField = "field_13" # Internal name of the address field
$duplicateAddressField = "DuplicateAddress" # Internal name of the flag field (True/False)
# Check if the list exists $list = Get-PnPList -Identity $listName -ErrorAction SilentlyContinue if (-not $list) { Write-Host "The list '$listName' does not exist at the site '$siteUrl'." }
Retrieve all items in the list (in batches if more than 5000 items exist)
$batchSize = 500
$allItems = @()
$hasMoreItems = $true
Get all list items in batches to handle large lists
while ($hasMoreItems) {
$items = Get-PnPListItem -List $listName -PageSize $batchSize -Fields $addressField, $duplicateAddressField
$allItems += $items
# Check if the number of items retrieved is less than the batch size
if ($items.Count -lt $batchSize) {
$hasMoreItems = $false
}
}
Group items by Address (trimmed, case-insensitive) to find duplicates
$groupedByAddress = $allItems | Group-Object -Property {
($_.FieldValues[$addressField] -as [string]).Trim().ToLower()
}
Debug: Show groups to check duplicates
foreach ($group in $groupedByAddress) {
Write-Host "Group: Address = $($group.Name), Count = $($group.Count)"
}
Loop through each group and check for duplicates
foreach ($group in $groupedByAddress) {
if ($group.Count -gt 1) {
Write-Host "Duplicates found for address: $($group.Name) - Count: $($group.Count)"
# Mark **all** items in the group as duplicates
foreach ($item in $group.Group) {
# Update the DuplicateAddress field to True for all duplicate items
Set-PnPListItem -List $listName -Identity $item.Id -Values @{$duplicateAddressField = $true}
Write-Host "Updated item with ID $($item.Id) - DuplicateAddress set to True"
}
}
}
Write-Host "Duplicate Address check complete."
Thanks.