Previously I have written a blog post on multiple ways to delete comments form a SharePoint page. There are scenarios to delete all comments from a page or few comments from the page. Or comments from specific user to be deleted from one page or multiple pages. This would not be simple as site owner or page owner can delete all comments or disable comments on the page.

I am sharing a PowerShell script which is used to delete comments from orphand users who are no longer part of the organization or you can list any specific users. I have used below PnP PowerShell module to remove the comments from all pages under the site pages library:

#connect to sharepoint online site
Connect-PnPOnline -Url "https://mstalk.sharepoint.com" -Interactive

#Name of list 
$listName= "Site Pages" 
$orphanedUserEmails = "orphanduser1@mstechtlak.com","orphanduser1@mstechtlak.com"

#Get all list items from list in batches
$listItems = Get-PnPListItem -List $listName -Fields "ID" -PageSize 500

foreach($item in $listItems)
{ 
    try
    {
        $comments = Get-PnPListItemComment -List $listName -Identity $item.["ID"]

        foreach($comment in $comments)
        {
            if($orphanedUserEmails -contains $comment.Author.LoginName.Replace("i:0#.f|membership|",""))
            {
               Remove-PnPListItemComment -List $listName -Identity $item["ID"] -Text $comment.Text -Force                
            }
        }
    }
    catch 
    {
        write-host -f Red "Error:" $_.Exception.Message
    }
}

Adnan, a distinguished professional, boasts an impressive track record as a Microsoft MVP, having achieved this prestigious recognition for the eighth consecutive year since 2015. With an extensive career spanning over 18 years, Adnan has honed his expertise in various domains, notably excelling in SharePoint, Microsoft 365, Microsoft Teams, the .Net Platform, and Microsoft BI. Presently, he holds the esteemed position of Senior Microsoft Consultant at Olive + Goose. Notably, Adnan served as the MCT Regional Lead for the Pakistan Chapter from 2012 to 2017, showcasing his leadership and commitment to fostering growth within the tech community. His journey in the realm of SharePoint spans 14 years, during which he has undertaken diverse projects involving both intranet and internet solutions for both private and government sectors. His impact has transcended geographical boundaries, leaving a mark on projects in the United States and the Gulf region, often collaborating with Fortune 500 companies. Beyond his roles, Adnan is a dedicated educator, sharing his insights and knowledge as a trainer. He also passionately advocates for technology, frequently engaging with the community through speaking engagements in various forums. His multifaceted contributions exemplify his dedication to the tech field and his role in driving its evolution.

Leave a Reply