Skip to content

Instantly share code, notes, and snippets.

@Toakan
Created November 24, 2025 17:29
Show Gist options
  • Select an option

  • Save Toakan/6d1a99d22f7d4339e6219936bd6ef510 to your computer and use it in GitHub Desktop.

Select an option

Save Toakan/6d1a99d22f7d4339e6219936bd6ef510 to your computer and use it in GitHub Desktop.
Getting Chat history from Teams
# Script to get Microsoft Teams chat history and export to CSV
# Requires Microsoft.Graph PowerShell module
# Import required modules
Import-Module Microsoft.Graph.Users -ErrorAction Stop
Import-Module Microsoft.Graph.Teams -ErrorAction Stop
# Connect to Microsoft Graph with required permissions
Write-Host "Connecting to Microsoft Graph..." -ForegroundColor Cyan -NoWelcome
Connect-MgGraph -Scopes "Chat.Read", "Chat.ReadWrite", "ChatMessage.Read"
# Get the current user's ID
Write-Host "Getting user information..." -ForegroundColor Cyan
$currentUser = Get-MgUser -UserId (Get-MgContext).Account
$userId = $currentUser.Id
Write-Host "Logged in as: $($currentUser.DisplayName) ($($currentUser.UserPrincipalName))" -ForegroundColor Green
# Function to list all chats for the current user
function Get-UserChats {
param(
[Parameter(Mandatory=$true)]
[string]$UserId
)
Write-Host "`nRetrieving your chats..." -ForegroundColor Cyan
$chats = Get-MgUserChat -UserId $UserId -All
$chatList = @()
foreach ($chat in $chats) {
$chatInfo = [PSCustomObject]@{
ChatId = $chat.Id
Topic = if ($chat.Topic) { $chat.Topic } else { "(No Topic)" }
ChatType = $chat.ChatType
CreatedDateTime = $chat.CreatedDateTime
}
$chatList += $chatInfo
}
return $chatList
}
# Function to get all messages from a specific chat
function Get-ChatMessages {
param(
[Parameter(Mandatory=$true)]
[string]$ChatId
)
Write-Host "`nRetrieving messages from chat..." -ForegroundColor Cyan
try {
$messages = Get-MgChatMessage -ChatId $ChatId -All
$messageList = @()
foreach ($message in $messages) {
$messageInfo = [PSCustomObject]@{
MessageId = $message.Id
CreatedDateTime = $message.CreatedDateTime
LastModifiedDateTime = $message.LastModifiedDateTime
MessageType = $message.MessageType
From = if ($message.From.User) { $message.From.User.DisplayName } else { "System" }
FromEmail = if ($message.From.User) { $message.From.User.UserIdentityType } else { "" }
Body = $message.Body.Content
BodyPreview = if ($message.Body.Content.Length -gt 100) { $message.Body.Content.Substring(0, 100) + "..." } else { $message.Body.Content }
Importance = $message.Importance
DeletedDateTime = $message.DeletedDateTime
}
$messageList += $messageInfo
}
return $messageList | Sort-Object CreatedDateTime
} catch {
Write-Host "Error retrieving messages: $_" -ForegroundColor Red
return $null
}
}
# Main execution
Write-Host "=== Microsoft Teams Chat History Export ===" -ForegroundColor Green
Write-Host ""
# Step 1: List all chats
$chats = Get-UserChats -UserId $userId
if ($chats.Count -eq 0) {
Write-Host "No chats found." -ForegroundColor Yellow
Disconnect-MgGraph
exit
}
Write-Host "`nFound $($chats.Count) chats:" -ForegroundColor Green
$chats | Format-Table -Property ChatId, Topic, ChatType, CreatedDateTime -AutoSize
# Step 2: Prompt for specific Chat ID or Teams URL
Write-Host "`nEnter the Chat ID or paste the Teams chat URL:" -ForegroundColor Yellow
$userInput = Read-Host
if ([string]::IsNullOrWhiteSpace($userInput)) {
Write-Host "No Chat ID or URL provided. Exiting." -ForegroundColor Red
Disconnect-MgGraph
exit
}
# Extract Chat ID from Teams URL if a URL was provided
$selectedChatId = $userInput
if ($userInput -match "https://teams\.microsoft\.com/l/message/([^/]+)") {
$selectedChatId = $matches[1]
Write-Host "Extracted Chat ID from URL: $selectedChatId" -ForegroundColor Cyan
} elseif ($userInput -match "19:[a-f0-9]+@thread\.v2") {
# Direct Chat ID format detected
$selectedChatId = $userInput
Write-Host "Using provided Chat ID: $selectedChatId" -ForegroundColor Cyan
} else {
Write-Host "Could not parse input. Please provide a valid Chat ID or Teams URL." -ForegroundColor Red
Disconnect-MgGraph
exit
}
# Verify the chat exists
$selectedChat = $chats | Where-Object { $_.ChatId -eq $selectedChatId }
if (-not $selectedChat) {
Write-Host "Chat ID not found in your chats." -ForegroundColor Red
Disconnect-MgGraph
exit
}
Write-Host "`nSelected chat: $($selectedChat.Topic) ($($selectedChat.ChatType))" -ForegroundColor Green
# Step 3: Get messages from the selected chat
$messages = Get-ChatMessages -ChatId $selectedChatId
if ($null -eq $messages -or $messages.Count -eq 0) {
Write-Host "No messages found in this chat or unable to retrieve messages." -ForegroundColor Yellow
Disconnect-MgGraph
exit
}
Write-Host "`nRetrieved $($messages.Count) messages" -ForegroundColor Green
# Step 4: Export to CSV
$timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$outputFile = Join-Path $PSScriptRoot "ChatHistory_$timestamp.csv"
$messages | Export-Csv -Path $outputFile -NoTypeInformation -Encoding UTF8
Write-Host "`nChat history exported successfully!" -ForegroundColor Green
Write-Host "File location: $outputFile" -ForegroundColor Cyan
Write-Host "`nTotal messages exported: $($messages.Count)" -ForegroundColor Green
# Disconnect from Microsoft Graph
Write-Host "`nDisconnecting from Microsoft Graph..." -ForegroundColor Cyan
Disconnect-MgGraph
Write-Host "`nDone!" -ForegroundColor Green
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment