Counting Private, Public, and Shared Channels in Microsoft Teams using Graph PowerShell

Managing Microsoft Teams effectively requires detailed insight into the structure and composition of teams and channels within your tenant. One important aspect is understanding the number of private, public, and shared channels that exist across all the teams in your tenant. This article provides a PowerShell script that leverages Microsoft Graph to count these channels, explains how the script works, suggests enhancements, discusses potential errors, and offers solutions.


Script to Count Private, Public, and Shared Channels

# Connect to Microsoft Graph
Connect-MgGraph -Scopes "Group.Read.All", "Channel.Read.All"

# Initialize counters
$privateChannelCount = 0
$publicChannelCount = 0
$sharedChannelCount = 0

# Retrieve all teams
$teams = Get-MgGroup -Filter "resourceProvisioningOptions/Any(x:x eq 'Team')" -Property Id, DisplayName -All

foreach ($team in $teams) {
    Write-Host "Processing Team: $($team.DisplayName)"

    # Retrieve all channels for the current team
    $channels = Get-MgTeamChannel -TeamId $team.Id -All

    foreach ($channel in $channels) {
        if ($channel.MembershipType -eq 'private') {
            $privateChannelCount++
        } elseif ($channel.MembershipType -eq 'standard') {
            $publicChannelCount++
        } elseif ($channel.MembershipType -eq 'shared') {
            $sharedChannelCount++
        }
    }
}

# Output the results
Write-Host "Private Channels: $privateChannelCount"
Write-Host "Public Channels: $publicChannelCount"
Write-Host "Shared Channels: $sharedChannelCount"

# Disconnect from Microsoft Graph
Disconnect-MgGraph

The Script Output


How the Script Works

  1. Connect to Microsoft Graph: The script starts by connecting to Microsoft Graph with the required permissions (Group.Read.All and Channel.Read.All). This allows the script to read information about groups and channels.
    Connect-MgGraph -Scopes "Group.Read.All", "Channel.Read.All"
  2. Initialize Counters: The script initializes counters for private, public, and shared channels.
    $privateChannelCount = 0
    $publicChannelCount = 0
    $sharedChannelCount = 0
  3. Retrieve All Teams: The script retrieves all Microsoft Teams by filtering groups with resourceProvisioningOptions set to Team.
    $teams = Get-MgGroup -Filter "resourceProvisioningOptions/Any(x:x eq 'Team')" -Property Id, DisplayName -All
  4. Process Each Team: For each team, the script retrieves all channels and increments the respective counters based on the channel's membership type.
    foreach ($team in $teams) {
        Write-Host "Processing Team: $($team.DisplayName)"
    
        # Retrieve all channels for the current team
        $channels = Get-MgTeamChannel -TeamId $team.Id -All
    
        foreach ($channel in $channels) {
            if ($channel.MembershipType -eq 'private') {
                $privateChannelCount++
            } elseif ($channel.MembershipType -eq 'standard') {
                $publicChannelCount++
            } elseif ($channel.MembershipType -eq 'shared') {
                $sharedChannelCount++
            }
        }
    }
  5. Output the Results: Finally, the script outputs the counts of private, public, and shared channels and disconnects from Microsoft Graph.
    Write-Host "Private Channels: $privateChannelCount"
    Write-Host "Public Channels: $publicChannelCount"
    Write-Host "Shared Channels: $sharedChannelCount"
    
    Disconnect-MgGraph

Enhancements

This script can be further enhanced in several ways:

  • Logging: Add logging to capture the output and store it in a file for future reference.
    $logPath = "C:\ChannelCounts.log"
    Write-Output "Private Channels: $privateChannelCount" | Out-File -FilePath $logPath -Append
    Write-Output "Public Channels: $publicChannelCount" | Out-File -FilePath $logPath -Append
    Write-Output "Shared Channels: $sharedChannelCount" | Out-File -FilePath $logPath -Append
  • Email Notification: Send an email with the results using Send-MailMessage.
    $emailBody = @"
    Private Channels: $privateChannelCount
    Public Channels: $publicChannelCount
    Shared Channels: $sharedChannelCount
    "@
    
    Send-MailMessage -To "admin@example.com" -From "reporter@example.com" -Subject "Microsoft Teams Channel Counts" -Body $emailBody -SmtpServer "smtp.example.com"
  • Detailed Reporting: Include more details such as the names of the teams and channels in the report.
  • Scheduling: Schedule this script to run at regular intervals using Task Scheduler or a similar service.

Possible Errors and Solutions

Permission Denied: Ensure the account running the script has the required permissions (Group.Read.All and Channel.Read.All).

Rate Limiting: If the script runs against a large number of teams, you might encounter rate limiting. Implement retries with exponential backoff.

function Invoke-WithRetry {
    param (
        [scriptblock]$ScriptBlock
        [int]$MaxRetries = 5
    )
    
    $retryCount = 0
    $success = $false
    while (-not $success -and $retryCount -lt $MaxRetries) {
        try {
            &$ScriptBlock
            $success = $true
        } catch {
            $retryCount++
            Start-Sleep -Seconds ([math]::Pow(2, $retryCount))
        }
    }
    if (-not $success) {
        throw "Operation failed after $MaxRetries retries."
    }
}

Connectivity Issues: Ensure the machine running the script has internet access and can reach the Microsoft Graph API endpoints.

Invalid Team ID: Handle scenarios where the team ID might be invalid or the team has been deleted during the script execution.

try {
    $channels = Get-MgTeamChannel -TeamId $team.Id -All
} catch {
    Write-Host "Failed to retrieve channels for Team: $($team.DisplayName)"
    continue
}


Conclusion

By using the provided script, administrators can effectively count and categorize the channels within their Microsoft Teams environment. This script is a powerful tool for gaining insights into the structure of Teams and can be customized and enhanced to meet specific organizational needs. Understanding the potential errors and their solutions ensures smooth execution and reliable results. Implementing such scripts not only helps in better management but also in proactive monitoring and planning for Microsoft Teams deployment.

For more PowerShell scripts and tips on managing Microsoft 365, visit M365Corner.com.


Related Articles:

Using Get-MgDirectoryRole in Graph PowerShell
Using Get-MgUserLicenseDetail in Graph PowerShell
Using Find-GraphMgCommand in Graph PowerShell
Connect to Microsoft 365 Using PowerShell
How to Create Bulk Users in Office 365 Using Graph PowerShell?
Create Microsoft 365 Group Using Microsoft Graph PowerShell
Block Microsoft 365 User Using Microsoft Graph PowerShell
Assign Microsoft 365 License Using Graph PowerShell
Microsoft 365 User Management Using Graph PowerShell
Checking Group Membership in Microsoft 365
Bulk Assign Microsoft 365 License
Find Inactive Users in Microsoft 365
Using Powershell Graph Search Query
Using Powershell Graph Filter Query
Using Where-Object In Graph PowerShell
Using Expand Property In Graph PowerShell
Using Select Object In Graph PowerShell
Using -Contains Operator In Graph PowerShell
Add User to Multiple Microsoft 365 Groups Using Graph PowerShell
Get Microsoft 365 User Location Using Graph PowerShell
Import Microsoft 365 Groups from CSV File Using Graph PowerShell
Microsoft 365 Group User Import Using Graph PowerShell

© m365corner.com. All Rights Reserved. Design by HTML Codex