Published on

Export chat from MS Team

Authors
  • avatar
    Name
    PatharaNor
    Twitter

Preparation

Installation

Install PowerShell for Shell :

brew install powershell openssl

Output :

Running `brew update --auto-update`...
==> Auto-updated Homebrew!
Updated 1 tap (homebrew/core).
==> New Formulae
aptos                    kubent                   quartz-wm                simdutf                  video-compare            xmodmap                  xrdb
bossa                    podsync                  ruby@3.1                 twm                      xinit                    xorg-server

You have 10 outdated formulae installed.
You can upgrade them with brew upgrade
or list them with brew outdated.

==> Tapping homebrew/cask
Cloning into '/usr/local/Homebrew/Library/Taps/homebrew/homebrew-cask'...
remote: Enumerating objects: 700983, done.
remote: Counting objects: 100% (209/209), done.
remote: Compressing objects: 100% (138/138), done.
remote: Total 700983 (delta 116), reused 162 (delta 71), pack-reused 700774
Receiving objects: 100% (700983/700983), 329.46 MiB | 2.74 MiB/s, done.
Resolving deltas: 100% (498283/498283), done.
Tapped 4139 casks (4,211 files, 351.8MB).
==> Caveats
To use Homebrew in PowerShell, set:
  Add-Content -Path $PROFILE.CurrentUserAllHosts -Value '$(/usr/local/bin/brew shellenv) | Invoke-Expression'

==> Downloading https://github.com/PowerShell/PowerShell/releases/download/v7.3.1/powershell-7.3.1-osx-x64.pkg
==> Downloading from https://objects.githubusercontent.com/github-production-release-asset-2e65be/49609581/81c4e6f9-8081-4b2a-9799-165382cda4db?X-Amz-Algorithm=AWS4-HMAC-SHA25
######################################################################## 100.0%
All formula dependencies satisfied.
==> Installing Cask powershell
==> Running installer for powershell; your password may be necessary.
Package installers may write to any location; options such as `--appdir` are ignored.
Password:
installer: Package name is PowerShell - 7.3.1
installer: Installing at base path /
installer: The install was successful.
🍺  powershell was successfully installed!
Warning: openssl@3 3.0.7 is already installed and up-to-date.
To reinstall 3.0.7, run:
  brew reinstall openssl@3

Enter PowerShell mode in console :

pwsh
PowerShell 7.3.1

PS >

Install PowerShell's dependencies :

Install-Module -Name PowerShellGet
Install-Module -Name PSWSMan
sudo pwsh -Command 'Install-WSMan'
Install-Module ExchangeOnlineManagement
Install-Module ExchangePowerShell
Install-Module Microsoft.Graph

Checking

Connection

Connect-ExchangeOnline -UserPrincipalName user@company.com

Output :

The module allows access to all existing remote PowerShell (V1) cmdlets in addition to the 9 new, faster, and more reliable cmdlets.

|--------------------------------------------------------------------------|
|    Old Cmdlets                    |    New/Reliable/Faster Cmdlets       |
|--------------------------------------------------------------------------|
|    Get-CASMailbox                 |    Get-EXOCASMailbox                 |
|    Get-Mailbox                    |    Get-EXOMailbox                    |
|    Get-MailboxFolderPermission    |    Get-EXOMailboxFolderPermission    |
|    Get-MailboxFolderStatistics    |    Get-EXOMailboxFolderStatistics    |
|    Get-MailboxPermission          |    Get-EXOMailboxPermission          |
|    Get-MailboxStatistics          |    Get-EXOMailboxStatistics          |
|    Get-MobileDeviceStatistics     |    Get-EXOMobileDeviceStatistics     |
|    Get-Recipient                  |    Get-EXORecipient                  |
|    Get-RecipientPermission        |    Get-EXORecipientPermission        |
|--------------------------------------------------------------------------|

To get additional information, run: Get-Help Connect-ExchangeOnline or check https://aka.ms/exops-docs

Send your product improvement suggestions and feedback to exocmdletpreview@service.microsoft.com. For issues related to the module, contact Microsoft support. Don't use the feedback alias for problems or support issues.

Get info of mailbox

Get-mailbox | select Displayname, WindowsEmailAddress

Output :

=============================================================

New update available!
You are using an older version of Exchange PowerShell cmdlets which may be using (soon to be deprecated) Basic authentication.
Please install version 2.0.6 of the ExchangeOnlineManagement module to upgrade to the latest version of cmdlets, which are REST based, more secure, reliant and performant than the remote PowerShell cmdlets that you are currently using.

For more information on the latest cmdlets released, visit: https://techcommunity.microsoft.com/t5/exchange-team-blog/exchange-online-powershell-v2-module-preview-now-more-secure/ba-p/2922946
To download the latest version of the module, visit https://www.powershellgallery.com/packages/ExchangeOnlineManagement/2.0.6-Preview5

============================================================


DisplayName            WindowsEmailAddress
-----------            -------------------
FirstName LastName user@company.com

Usage

Create output directory name ./data and create PowerShell script (*.ps1) then let's try script below.

List chat ID

Import-Module Microsoft.Graph.Teams
$RequiredScopes = @("Chat.ReadBasic", "Chat.ReadWrite")
Connect-MgGraph -Scopes $RequiredScopes

get-mgchat | foreach-object {
    write-host $_.Id
    # $_
}

#and now close/disconnect
Disconnect-MgGraph

Get chat topic

Import-Module Microsoft.Graph.Teams
$RequiredScopes = @("Chat.ReadBasic", "Chat.ReadWrite")
Connect-MgGraph -Scopes $RequiredScopes

# get-mgchat
# get-mgchat -ChatId 19:meeting_ZWMyYWU...LTliZWMtN2RhNDE2OTlmNGQ2@thread.v2

$mychats = get-mgchat -all -PageSize 50
$all_chat_info = @() #force-setting to an array
$all_chat_info = foreach ($chat in $mychats) {
    $chat.Topic
}

$all_chat_info | format-table

#and now close/disconnect
Disconnect-MgGraph

Export chat

All contents will be exported to ./data into .csv file format. For the file name, I used topic name to be file name :

Import-Module Microsoft.Graph.Teams
$RequiredScopes = @("Chat.ReadBasic", "Chat.ReadWrite")
Connect-MgGraph -Scopes $RequiredScopes

If (Test-Path -Path "./data") { Get-ChildItem "./data" -Include * -Recurse | ForEach  { $_.Delete()} }
Else { New-Item -Path "./" -Name "data" -ItemType "directory" }

$tzone = Get-TimeZone
$mychats = get-mgchat -all -PageSize 50
$all_chat_info = @() #force-setting to an array
$all_chat_info = foreach ($chat in $mychats) {

    #set some details about the chat itself for the later query
    $chatname = $chat.Topic
    $members = $chat.Members
    $chattype = $chat.chattype

    If($chatname.Length -gt 0) {
        Write-Host "Processing on topic '$chatname'..."
    }

    $recentchatmessages = get-mgchatmessage -ChatId $chat.id -top 999 -pagesize 50
    $fileName = $chatname -Replace "[^A-Za-z0-9_]", ""
    Add-Content "./data/$($fileName).csv" ""

    If($chatname.Length -gt 0) {
        Add-Content "./data/topic-mapping.txt" "$chatname => $fileName.csv"
    }

    $log = $recentchatmessages | select `
    @{Label='LastModified';Expression={($_.LastModifiedDateTime.tolocaltime())}}, `
    @{Label='ChatName';Expression={($chatname)}}, @{Label='members';Expression={($members)}}, @{Label='ChatType';Expression={($chattype)}}, `
    @{Label='From';Expression={($_.from.user.displayname)}}, @{Label='Body';Expression={ ($_.Body.content -split '\n')[0] -replace '<[^>]+>',''}}

    $log `
    # | Select-Object -Property Name, Title, Department `
    | Export-Csv -path "./data/$($fileName).csv" -NoTypeInformation

    $log
}

# $all_chat_info | format-table

$all_chat_info `
| Export-Csv -path "./data/merged.csv" -NoTypeInformation

#and now close/disconnect
Disconnect-MgGraph

Write-Host "Finished"

Enjoy!!!

"LastModified","ChatName","members","ChatType","From","Body"
"MM/DD/YYYY HH:mm:ss","ROOM_NAME",,"group","MEMBER1","CHAT_MESSAGE1"
"MM/DD/YYYY HH:mm:ss","ROOM_NAME",,"group","MEMBER2","CHAT_MESSAGE2"
"MM/DD/YYYY HH:mm:ss","ROOM_NAME",,"group","MEMBER1","CHAT_MESSAGE3"
"MM/DD/YYYY HH:mm:ss","ROOM_NAME",,"group","MEMBER1","CHAT_MESSAGE4"
"MM/DD/YYYY HH:mm:ss","ROOM_NAME",,"group","MEMBER2","CHAT_MESSAGE5"
...