Getty Images
Microsoft Teams monitoring tips for admins
Learn how to use PowerShell to set up an automated way to check for suspicious activity in the Microsoft chat service to avoid security and compliance issues.
Organizations increasingly rely on Microsoft Teams for collaboration and communication. As the admin, it's your job to make this service efficient and secure.
The standard Microsoft Teams admin interface has basic monitoring, but admins often need more advanced capabilities. Using PowerShell is one way to gain deeper insights into the Teams environment by using automation to build enhanced monitoring capabilities. PowerShell offers an extensive set of tools for administrators to run commands beyond what the graphical interface can do. With PowerShell, you can automate regular tasks, monitor security incidents and create detailed reports. By utilizing PowerShell and the Microsoft Graph API, administrators can access deeper insights and have more control over Microsoft Teams. This tutorial explains how to set up PowerShell for Microsoft Teams monitoring, how to perform basic monitoring tasks and how to execute advanced security and compliance audits.
How to set up PowerShell for to monitor Microsoft Teams
To start the monitoring process for Microsoft Teams, use two PowerShell modules. The main module is MicrosoftTeams, which contains the cmdlets designed for Teams management and monitoring. The Microsoft.Graph module is also used to handle user and group management tasks.
To install the MicrosoftTeams module, open a PowerShell session with administrative privileges and run the following command.
Install-Module -Name MicrosoftTeams -Force -AllowClobber
This command deploys the latest version of the MicrosoftTeams module from PowerShell Gallery. The -Force parameter executes the install even if a previous version exists, and -AllowClobber resolves conflicts with other modules.
Monitoring tasks that involve user and group management requires the Microsoft.Graph module. Install it using the following command.
Install-Module -Name Microsoft.Graph -Force
This PowerShell module performs multiple tasks related to Microsoft Teams, such as retrieving user properties and managing group memberships.
After installation, import the modules into your PowerShell session.
Import-Module MicrosoftTeams
Import-Module Microsoft.Graph
Authentication methods with PowerShell and Microsoft Teams
It's important to understand how to connect to the Microsoft Teams service securely with PowerShell. There are several methods, each with its own security implications.
Interactive login
The most straightforward authentication method is interactive login. You manually enter your credentials each time you run a PowerShell script. Use the following command to authenticate.
Connect-MicrosoftTeams
This command prompts for a username and password, which is easy but unsuited for automated tasks or scripts.
Service principal
For more secure and automated access, you can use a service principal, which is an identity created with applications, hosted services and automated tools to access specific resources. The following are the steps to set it up:
- Create an Entra ID app registration, and configure it with the necessary API permissions for Microsoft Teams.
- Generate a self-signed certificate, or use an existing one.
- Upload the certificate to the app registration, and load it into your workstation.
- Use the corresponding information with the app's ID to authenticate in PowerShell.
Here is an example command.
$clientId = "Your-App-ID"
$tenantId = "Your-Tenant-ID"
$certThumbprint = "Your-Certificate-Thumbprint"
Connect-MicrosoftTeams `
-ApplicationId $clientId `
-TenantId $tenantId `
-CertificateThumbprint $certThumbprint
This method establishes an authenticated connection to Microsoft Teams, making it ideal for scheduled tasks and scripts.
Managed identities for Azure-hosted environments
If you run PowerShell scripts within an Azure environment, such as Azure Functions or Azure Automation, then managed identities are another option to authenticate to Microsoft Teams.
Managed identities eliminate the need for credential management to make them safer for use in automated scripts.
A managed Identity authenticates to the Azure resource and grants it permissions to access Microsoft Teams. The following PowerShell command authenticates to Microsoft Teams using managed identity.
Connect-MicrosoftTeams -ManagedIdentity
How to perform Microsoft Teams monitoring commands
As the organization's admin, it's important to understand how to work with the organization's teams and channels in Microsoft Teams. PowerShell makes it simple to retrieve and manage these lists, enabling you to track platform changes and overall team activity.
How to list all teams
To retrieve a list of all teams within your organization, use the Get-Team cmdlet.
$teams = Get-Team
$teams | Select-Object DisplayName, MailNickName, Visibility, Description
You can use PowerShell to filter the output based on properties, such as the team's name, mail nickname, visibility (public or private) and description. This information helps monitor team creation to ensure proper governance.
How to retrieve team channels
To list all channels within a specific team, use the Get-TeamChannel cmdlet.
$teamId = (Get-Team | Where-Object { $_.DisplayName -eq "Contoso" }).GroupId
Get-TeamChannel `
-GroupId $teamId
This command assists with monitoring channel creation to keep them aligned with your organization's communication policies.
How to detect changes in team memberships
It's important to keep tabs on team memberships from a security perspective, but it's another way to be sure the right people have access to the correct information. PowerShell automates the work required to detect and report on these membership changes.
Find team members with PowerShell
If you need to review the current membership of a team, which is helpful for periodic audits, you can use the following PowerShell command to list the members of a specific team.
Get-TeamUser -GroupId $teamId
Monitor membership changes
PowerShell can discover when modifications to team memberships occur by comparing the current list of members with a previously stored list.
The following script compares the current membership list with an older one stored in a CSV file, highlighting any additions or removals. The Compare-Object cmdlet finds the differences and outputs the results. If the arrow points to the right, then the names are new members who were added after the CSV list was created. If an arrow points left, then it indicates the person had been in the CSV list but is no longer a current team member. If the script shows equal signs, then the user's membership status did not change.
Get-TeamUser -GroupId $teamId | Export-Csv "PreviousMembers.csv"
$previousMembers = Import-Csv "PreviousMembers.csv"
$currentMembers = Get-TeamUser -GroupId $teamId
Compare-Object `
-ReferenceObject $previousMembers `
-DifferenceObject $currentMembers `
-Property User
How to perform security and compliance monitoring in Microsoft Teams
As collaboration tools, such as Microsoft Teams, become more integral to business operations, it becomes more important to keep the platform secure while maintaining compliance. PowerShell scripts can monitor for security incidents and enforce compliance policies to avoid unexpected surprises with the Microsoft Teams environment.
PowerShell commands to detect security incidents
Administrators are crucially responsible for monitoring potential security events. PowerShell uncovers these suspicious activities that might indicate a breach.
Monitoring guest access
As an enterprise collaboration tool, Microsoft Teams connects the organization to external partners. Guest access should undergo a review process to check permissions. The Get-TeamGuestSettings cmdlet helps audit guest access settings across your teams.
$team = Get-Team | `
Where-Object { $_.DisplayName -eq "Contoso" } | `
Select-Object *
$guestSettings = @{
AllowCreateUpdateChannels = $team.AllowGuestCreateUpdateChannels
AllowDeleteChannels = $team.AllowGuestDeleteChannels
}
$guestSettings
This PowerShell script checks guest users have access to certain features, such as creating channels or editing messages, and whether these permissions align with your organization's security policies.
Detecting suspicious activity
You can use PowerShell to monitor Microsoft Teams for unusual activity, such as frequent file downloads or sharing with external users, by using the ExchangeOnline PowerShell module, which works in tandem with the MicrosoftTeams module.
Connect-ExchangeOnline `
-UserPrincipalName [email protected]
$searchParams = @{
StartDate = (Get-Date).AddDays(-7)
EndDate = Get-Date
RecordType = "SharePointFileOperation"
Operations = "FileDownloaded"
}
Search-UnifiedAuditLog @searchParams |
ForEach-Object {
$auditData = $null
$auditData = $PSItem.AuditData | ConvertFrom-Json
[PSCustomObject]@{
Operation = $PSItem.Operations
User = $auditData.UserId
FileName = $auditData.ObjectId
SiteUrl = $auditData.SiteUrl
FileUrl = $auditData.SourceFileName
FilePath = $auditData.SourceRelativeUrl
TimeStamp = $auditData.CreationTime
}
} | Format-Table -AutoSize
This PowerShell script retrieves user activities related to file downloads within a specified date range. By monitoring these activities, you can quickly identify and respond to potential security threats.
Finding potential risks
In addition to detecting security incidents, PowerShell helps to identify and mitigate potential risks that could compromise your Microsoft Teams environment.
Checking for uncommon activities
Use PowerShell to monitor Microsoft Teams activities that stand out for unusual or noncompliant behavior, such as sharing files. The following example uses the Microsoft Graph PowerShell cmdlets to check the files within a team. The script probes the connected SharePoint Online site and then iterates the documents library to check all files and subfolders for externally shared links.
$teamName = "HRTeam"
$site = Get-MgSite -SiteId "{tenant}.sharepoint.com:/sites/$teamName"
$drives = Get-MgSiteDrive -SiteId $site.Id
$documentsDrive = $drives | Where-Object { $_.Name -eq "Documents" }
# Retrieve the root folder's items (files and subfolders)
$files = Get-MgDriveItem -DriveId $documentsDrive.Id -DriveItemId root -ExpandProperty children
# Initialize an array to store the results
$results = @()
foreach ($file in $files.children)
{
$uri = "https://graph.microsoft.com/v1.0/drives/$($documentsDrive.Id)/items/$($file.Id)/permissions"
$sharingLinks = Invoke-MgGraphRequest -Uri $uri -Method Get
# Iterate through each sharing link and create a custom object with the file name and link information
foreach ($link in $sharingLinks.value) {
$results += [PSCustomObject]@{
FileName = $file.Name # Use the actual file name
LinkId = $link.Id
Roles = $link.Roles -join ', '
GrantedTo = $link.GrantedTo.User.DisplayName
LinkType = $link.Link.Type
LinkUrl = $link.Link.WebUrl
}
}
}
# Output the results as a table
$results | Format-Table -AutoSize
Reviewing actions for compliance
PowerShell can automate compliance checks, ensuring that all teams adhere to your organization's policies. You can also use PowerShell to retrieve a list of actions performed within Microsoft Teams to validate the types of actions and functions performed within the collaboration service.
$startDate = (Get-Date).AddDays(-7)
$endDate = Get-Date
$teamsAuditLogs = Search-UnifiedAuditLog -StartDate $startDate -EndDate $endDate -RecordType "MicrosoftTeams" -ResultSize 1000
# Display the logs
$teamsAuditLogs | Select-Object CreationDate, UserIds, Operations, AuditData | Format-Table -AutoSize
$teamsAuditLogs | ForEach-Object {
$auditData = $_.AuditData | ConvertFrom-Json
[PSCustomObject]@{
User = $auditData.UserId
Operation = $auditData.Operation
CreationDate = $_.CreationDate
Item = $auditData.ObjectId
Details = $auditData.Details
}
} | Format-Table -AutoSize
This script uses the ExchangePowerShell module to search the previous seven days in the audit logs and identify a team's specific actions, such as types of operations executed by a user and when they were performed.
Automation tools ease the monitoring workload
Using PowerShell, you can access detailed information about Microsoft Teams and channels, track changes in team memberships and monitor user activities to protect your organization's data. Integration with the Microsoft Graph API makes a wide range of data available to catch suspicious activities, such as abuse of guest access and data deletion. This combination opens the way to create real-time alerts for potentially problematic actions and automate production of comprehensive monitoring reports.
By incorporating these automated inspections into your regular management of Microsoft Teams, you maintain an efficient collaboration platform that meets the organization's security and compliance standards.
Liam Cleary is founder and owner of SharePlicity, a technology consulting company that helps organizations with internal and external collaboration, document and records management, business process automation, automation tool deployment, and security controls and protection. Cleary's areas of expertise include security on the Microsoft 365 and Azure platforms, PowerShell automation, and IT administration. Cleary is a Microsoft MVP and a Microsoft Certified Trainer.