Skip to content

Automating the Removal of Users from Microsoft Teams Shared Channels with PowerShell

Automating User Removal from Microsoft Teams Shared Channels

Section titled “Automating User Removal from Microsoft Teams Shared Channels”

Managing user memberships in Microsoft Teams shared channels is an essential task for IT administrators, especially in large organizations where multiple teams and shared channels are used extensively. This PowerShell script automates the process of identifying shared channels within Teams, filtering out specific users, and removing them from the channel memberships.


This script automates the process of managing shared channel memberships across Teams. It performs the following actions:

FunctionDescriptionBusiness Value
Channel DiscoveryIdentifies all shared channelsComplete visibility
User FilteringFilters users by domain criteriaTargeted removal
Automated RemovalRemoves filtered usersSecurity enforcement
Process LoggingRecords all actionsAudit trail
FeatureCapabilityImpact
Domain-Based FilteringTargets specific email domainsPrecise user selection
Channel Type DetectionDistinguishes hosted vs incoming channelsComprehensive coverage
Batch ProcessingHandles multiple teams simultaneouslyScalable solution
Error HandlingLogs processing issuesTroubleshooting support

Before running the script, ensure you have:

RequirementDescriptionPurpose
Microsoft Teams PowerShell ModuleInstalled and configuredAPI access
Administrative PermissionsChannel management rightsUser removal capability
Shared ChannelsConfigured in Teams environmentTarget resources

The core of the script is a function called Process_TeamChannel. This function is designed to:

  • Retrieve all shared channels for a given team
  • Identify the type of shared channel (whether it is hosted by the team or incoming from another team)
  • Filter out specific users based on their email domains
  • Remove those users from the shared channel
Terminal window
Function Process_TeamChannel {
param (
[string]$TeamId,
[string]$OutputCSV
)
$channels = Get-TeamAllChannel -GroupId $TeamId -MembershipType Shared
foreach ($channel in $channels) {
$ChannelName = $channel.DisplayName
$HostTeamId = $channel.HostTeamId
$SharedChannelType = if ($HostTeamId -eq $TeamId) {
"Team hosted channel"
} else {
"Incoming channel"
}
}
}

The Get-TeamAllChannel cmdlet retrieves all shared channels associated with the team, which is identified by its TeamId.

The script then retrieves the members of the shared channel using the Get-TeamChannelUser cmdlet. It filters out users who belong to specific email domains.

Terminal window
$Membership = Get-TeamChannelUser -GroupId $HostTeamId -DisplayName $ChannelName
$Membership = $Membership | Where-Object {
($_.User -Like "*@XXX.onmicrosoft.com") -or
($_.User -Like "*@XXX.onmicrosoft.com")
}

This filtering step ensures that only users from the specified domains are targeted for removal.

Once the users are identified, the script removes them from the shared channel using the Remove-TeamChannelUser cmdlet.

Terminal window
foreach ($Member in $Membership) {
Write-Output "Removing $($Member.User) from $($_.'Team Name') \ $ChannelName"
Remove-TeamChannelUser -DisplayName $ChannelName -GroupId $TeamId -User $($Member.User) -Role $($Member.Role)
}

For each user, a message is logged indicating which user is being removed from which shared channel. The actual removal is handled by Remove-TeamChannelUser.

After defining the Process_TeamChannel function, the script applies this function to all teams within the tenant using the Get-Team cmdlet.

Terminal window
# Process all teams
Get-Team | ForEach-Object {
$TeamId = $_.GroupId
Process_TeamChannel -TeamId $TeamId
}

This loop ensures that all teams in the environment are scanned for shared channels, and the targeted users are removed from those channels.


This script is particularly useful in scenarios where:

ScenarioApplicationValue
Domain-Based Access ControlRemove users from specific domainsEnforce access policies
Partner ManagementClean up external user accessMaintain security boundaries
Policy EnforcementAutomate compliance requirementsReduce manual effort
Security HardeningRemove unauthorized accessImprove security posture

Imagine that you need to remove external users (from certain partner domains) who were previously invited to your organization’s shared channels. Instead of manually searching for and removing these users from each team and channel, this script automates the entire process, ensuring that your shared channels remain secure and compliant with internal policies.


Best PracticeDescriptionImplementation
Test EnvironmentVerify script functionality before productionReduce deployment risks
Error MonitoringReview script output logsEnsure successful execution
Membership BackupExport current memberships before removalMaintain audit trail
Domain ValidationConfirm target domains are correctPrevent accidental removals

Why Automate Shared Channel Membership Management?

Section titled “Why Automate Shared Channel Membership Management?”

Managing user access across multiple shared channels can be time-consuming, especially if done manually.

ChallengeManual ProcessAutomated Solution
Time InvestmentHours per cleanup cycleMinutes of processing
AccuracyRisk of missing usersComplete coverage
ConsistencyVariable applicationStandardized process
AuditabilityManual documentationAutomatic logging
BenefitDescriptionImpact
Access ControlEnforce domain-based policiesReduce security risks
ComplianceMeet regulatory requirementsMaintain standards
GovernanceCentralized access managementImprove control
Audit TrailAutomated action loggingSupport investigations

The script distinguishes between two types of shared channels:

Channel TypeDescriptionProcessing Approach
Team HostedChannel owned by the teamDirect processing
IncomingChannel shared from another teamExternal processing
Filter CriteriaTarget UsersRemoval Logic
Domain Pattern*@XXX.onmicrosoft.comPattern matching
Multiple DomainsVarious partner domainsOR logic applied
Exact MatchSpecific domain namesPrecise targeting

Key Takeaway: This PowerShell script provides an efficient way to manage shared channel memberships in Microsoft Teams by automating the process of identifying and removing specific users. By integrating with Microsoft Teams PowerShell, the script ensures that all teams and shared channels are processed, saving time and reducing the risk of errors in large environments.

Whether you’re performing routine audits, enforcing compliance, or managing external user access, this script offers a powerful tool for keeping your Teams environment secure and well-organized. By customizing the script to match your organization’s needs, you can automate complex tasks and focus on higher-level administrative responsibilities.