I am trying to get my teams chat messages for the past x days. It runs, but it's incredibly slow because it looks for EVERY chat I've ever made, iterates through each one, then filters down to the past day. (code below).
Reading online, I can see that the Graph API allows filtering on get-mgchat (lastModifiedDatetime ge datetime), but I can't get it to work. Even something like this says "invalid filter".
get-mgchat -filter "lastModifiedDateTime ge '2023-02-01T07:13:28.000'"
Get-MgChat_List1: Invalid filter clause
Is there some way to do this? It's a bit mind-boggling that I can't say "only look at recent messages or chats that have recent messages"
$RequiredScopes = @("Chat.ReadBasic", "Chat.ReadWrite")
Connect-MgGraph -Scopes $RequiredScopes
#this nests and walks through properly, strips HTML, but this is be slow. And shows more than one line per message, even when I try not to.
#By default you can get all your chats by running get-mgchat. -all and -pagesize 50 is required for the module to paginate the request and get you everything. But in my case it grabbed all 2000 chats. The -first 5 is for testing.
$tzone = Get-TimeZone # conversion from GMT to local time. https://jdhitsolutions.com/blog/powershell/7962/convert-to-local-time-with-powershell/
$mychats = get-mgchat -all -PageSize 50
$all_chat_info = @() #force-setting to an array
$all_chat_info = foreach ($chat in $mychats) {
$chatinfo = get-mgchat -ChatId $chat.id #get base details about the CHAT itself
#set some details about the chat itself for the later query
$chatname = $chat.Topic
$members = $chat.Members
$chattype = $chat.chattype
#now get every message from that chat since midnight yesterday. Note LastModifiedDateTime is GMT. The jdhit page says -($tzone...), but all I had to do was .tolocaltime() ... I think.
#the -top 200 -pagesize 50 is to get the most recent 200 messages, and again you have to paginate.
$recentchatmessages = get-mgchatmessage -ChatId $chat.id -top 500 -pagesize 50 |where {$_.LastModifiedDateTime.tolocaltime() -gt (get-date).date.AddDays(-5)} # all from after midnight yesterday |select -first 5
#and now use select expression to add the above fields and parse the below fields, stripping out HTML (but I can't seem to only get the first line in OGV)
$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 '<[^>]+>',''}}
#@{Label='From';Expression={($_.from.user.displayname)}}, @{Label='Body';Expression={( ($_.Body.content -replace '<[^>]+>','').split([Environment]::NewLine)|select -first 1)}}
}
$all_chat_info|export-csv -path c:\temp\teams_20230224 #format-table