I was recently asked by a colleague about whether it was possible to use PowerShell to remove a group of users in an Active Directory group from all Microsoft Teams’ Teams in an organization. A bit of Googling did not yield any results so I quickly wrote one that performs the following:
- Uses Get-ADGroupMember to export a list of users’ User Principal Name from an Active Directory group to a txt file
- Uses the exported list of UPNs to get the list of Teams each user belongs to
- Write the list of Teams the user belongs to into a txt file with their UPN as the file name
- Remove the user from every Team they belong to
The following is the PowerShell script.
Obtain list of users in an AD Group (you can run this on a domain controller and copy the file to where you will connect to O365)
Get-ADGroupMember -Identity "Board Members" | %{Get-ADUser $_.SamAccountName | foreach { $_.userPrincipalName }} > C:ScriptsUPNofADGroup.txt
**The example above retrieves users from a AD Group named “Board Members”
Connect to Microsoft Teams environment
Connect-MicrosoftTeams
https://docs.microsoft.com/en-us/powershell/module/teams/connect-microsoftteams?view=teams-ps
Use the list of UPNs to export the Teams they belong to then remove them from the Teams
ForEach ($userToRemove in Get-Content C:ScriptsUPNofADGroup.txt)
{
$exportedFile = "C:Scripts" + $userToRemove + ".txt"
Get-Team -User $userToRemove | FT -AutoSize > $exportedFile
$GroupIDList = Get-Team -User $userToRemove | Select *GroupID*
Foreach ($GroupID in $GroupIDList)
{
Remove-TeamUser -GroupID $GroupID.GroupID -user $userToRemove
}
}
————————————————————————————————–
Hope this helps anyone who may be looking for a script like this.