I did an easy script for a case when disabled user accounts are saved during a sometime. The case was to remove this users from all membership in Microsoft Teams. An extension attribute is used for all accounts that is in this disabled state.

ExtentionAttribute7 = “Sleep”

To be able to run this script you need to import 2 modules in Azure Automation

  • MicrosoftTeams
  • ExchangeOnlineManagement

You will also need to create a service account with administrator roles of Microsoft Teams and Exchange Online.

#Get credantial from Azure Automation
$cred = Get-AutomationPSCredential -Name "keyvaultaccount1"

#Connect to both Exchange Online and Microsoft Teams
Connect-ExchangeOnline -Credential $cred
Connect-MicrosoftTeams -Credential $cred

#Get all users that is in the sleep state
$sleepusers = get-mailbox -filter ("customattribute7 -eq 'sleep') -ResultSize unlimited | select primarysmtpaddress

#Ta bort användare som är inaktiva från befintliga Teams
Foreach ($user in $sleepusers) {

    If ((Get-Team -User $user.primarysmtpaddress) -ne $null) {
        $teams = Get-Team -User $user.primarysmtpaddress
            foreach ($team in $teams){
                Remove-TeamUser -GroupId $team.GroupId -User $user.PrimarySmtpAddress
                Write-Output "$($user.PrimarySmtpAddress) is removed from team $($team.DisplayName)"
                }
        Write-Output "$($user.PrimarySmtpAddress) has been removed from $($teams.Count)"}
    else {
        Write-Output "$($bu.PrimarySmtpAddress) is not member of a team"
        }
    }