How to Remove Teams Chat Threads with PowerShell

Remove Problematic Chat Threads with the Remove-MgChat Cmdlet

Recently, a fellow MVP was looking for a way to remove Teams chats from user accounts. Someone apparently created a group chat, added everyone in the organization, and proceeded to spam the group with some “interesting” thoughts. It’s the kind of thing that we used the now-deprecated Search-Mailbox cmdlet to clean up. Microsoft’s current answer for email cleanup is Purview Priority Cleanup, but that solution doesn’t support Teams.

In any case, I pointed my colleague to a article I wrote in September 2023. The article describes an Azure Automation runbook that scans user accounts to find chat threads deemed problematic by the organization and calls the Remove-MgChat cmdlet to remove the offending chats.

Time to Improve Old Code

I hate looking at old code, especially old code written by me, especially when that code was written to prove a principal instead of being especially useful. It was time to crack open Visual Studio Code to fix some obvious issues (like replacing beta cmdlets with production cmdlets from the latest version of the Microsoft Graph PowerShell SDK) and add functionality. As is the nature of code updates, I ended up doing more work than anticipated to:

  • Add better error checking.
  • Refine the set of accounts processed by the script to just the set with licenses that include the Teams service plan.
  • Check for problem text in the body of chat messages rather than just the name of chat topics.
  • Expand the set of chats checked to include one-on-one conversations. Previously only group and meeting chats were checked.
  • Use the ImportExcel module (if available) or ConvertTo-CSV cmdlet to create an output file that ends up as an attachment for the email sent at the end of the script (Figure 1).
  • Generally, smarten up the code whenever I saw an opportunity to improve something.

Email to report deleted chat threads.
Figure 1: Email to report deleted chat threads

Finding Chat Threads, Chat Messages, and Removing Unwanted Material

The code uses the Get-MgUserChat cmdlet to fetch chat threads for a user. One change I made is to limit the chats to those created in the last month on the basis that problematic chat threads are usually reported soon after they’re created. It’s easy to adjust the filter used to find chats, but remember that the bigger the period searched, the longer it will take Get-MgUserChat to find the chat threads.

Examining the chat threads will find problems in chat topics (names). To find problems in the actual messages, we need to call Get-MgChatMessage. There can be many messages in a chat thread, and a fast method is needed to check the content of each message. A compiled regex pattern is a good choice in these scenarios. Here’s what I did:

[array]$Topics = "Management are idiots", "Sensitive Stuff", "Project Aurora", "Stock tips", "Inappropriate content"
$Pattern = ($Topics | ForEach-Object {[regex]::Escape($_)}) -join "|"
$Regex = [regex]::new($Pattern, [System.Text.RegularExpressions.RegexOptions]::IgnoreCase)

To process the messages in a chat thread, we do the following to extract the content from each message, strip the HTML tags from the content, and check the content against the regex pattern:

[array]$Messages = Get-MgChatMessage -ChatId $Chat.Id -All
ForEach ($Message in $Messages) {
  # Strip out HTML tags
  $Content = ($Message.Body.Content -replace '<[^>]+>', '')
  # Check messages to see if they contain any of the topics we're looking for.    
  # If so, the thread should be deleted. We only need one message to match to 
  # delete the thread, so we can stop checking after the first match.
  If ($Regex.IsMatch($Content) -and $DeleteThread -eq $false) {
  Write-Output ("Found chat message with matching content in chat {0} for user {1}" -f $Chat.Id, $User.displayName)
  $DeleteThread = $true
  $TopicFound = "Content"
  }
}

Once the code finds a problem in a chat thread or individual message, it flags the thread for deletion. Remove-MgChat performs the actual removal against the Teams message store. It takes a little time before the deletion synchronizes down to clients to remove the thread from user view.

Getting the Code

You can download the updated script from the Office 365 for IT Pros GitHub repository. The code will run interactively (in app-only mode unless you only want to process Teams chats for the signed-in user) or as an Azure Automation runbook. The runtime environment needs the authentication, users, and Teams modules from the Microsoft Graph PowerShell SDK. The automation account must be assigned the application Graph permissions listed in the script.

I’m sure that people will have ideas of how to improve the script. Don’t be shy about discussing those ideas in GitHub.


Need help to write and manage PowerShell scripts for Microsoft 365, including Azure Automation runbooks? Get a copy of the Automating Microsoft 365 with PowerShell eBook, available standalone or as part of the Office 365 for IT Pros eBook bundle.

One Reply to “How to Remove Teams Chat Threads with PowerShell”

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.