How to get Teams last signin activity and then remove license?

Damien 20 Reputation points
2024-01-25T07:39:35.5766667+00:00

I am trying to automate disabling Microsoft Teams licenses for users not connected for more than 180 days. In order to achieve this, I currently try to extract a report of users by signin activity, and then based on this select those with an activity greater than 6 months and remove their license. My current (not working) code is the following:

get-mguser -All ` 
-property signinactivity | Select-Object DisplayName -expandproperty signinactivity | Export-CSV "C:\temp\LastActivity.csv" -NoTypeInformation 
$InputFile = "c:\temp\LastActivity.csv" 
[array]$Users = Import-CSV $InputFile 
If (LastSignInDateTime -gt 6 months) 
	ForEach ($User in $Users) 
	{ 
    try 
    { 
        $License = Set-MgUserLicense -UserId $User.UPN -AddLicenses @() -RemoveLicenses @('18181a46-0d4e-45cd-891e-60aabd171b4e') -ErrorAction:Continue; 
    } 
    catch 
    { 
        Write-Warning -Message "Script failed while attempting to set the licence for $($User.UPN). Aborting."; 
        throw; 
    } 
	}

I see two main issues: first is the signinactivity I obtain which is not the Teams last signinactivity. The second is the command If (LastSignInDateTime -gt 6 months) that obviously does not work as is, I do not find how to make it work based on the report generated previsouly. Does anyone see how I can tweak my code to achieve the desired result?

Microsoft Teams
Microsoft Teams
A Microsoft customizable chat-based workspace.
8,659 questions
PowerShell
PowerShell
A family of Microsoft task automation and configuration management frameworks consisting of a command-line shell and associated scripting language.
1,853 questions
0 comments No comments
{count} votes

Accepted answer
  1. Vasil Michev 90,881 Reputation points MVP
    2024-01-25T08:48:12.55+00:00

    The signinactivity property does not represent Teams activity, as you've noted. If that's what you are interested in, best leverage the Teams activity report:

    Invoke-MgGraphRequest -Uri "https://graph.microsoft.com/beta/reports/getTeamsUserActivityUserDetail(period='D7')?`$format=application/json"
    

    Or go the easy route and "borrow" Tony's code here: https://office365itpros.com/2022/08/08/microsoft-365-user-activity-2022/


0 additional answers

Sort by: Most helpful