Get-AllTeamsUsers.psm1

function Get-AllTeamsUsers
{
    <#
    .SYNOPSIS
    Retrieves all users from Microsoft Teams.
 
    .DESCRIPTION
    This function retrieves a list of all users from Microsoft Teams, including their group memberships.
 
    .NOTES
    Author: Eric Meinders
    Version: 1.0
    #>


    [cmdletbinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param()
    
    # Verify if the MicrosoftTeams module is installed, install if not
    BEGIN
    {
        try
        {
            Get-InstalledModule -Name MicrosoftTeams -ErrorAction Stop > $null
        }
        catch 
        {
            Write-Warning "MicrosoftTeams module not found."
            if ($PScmdlet.ShouldProcess("MicrosoftTeams","Install-Module"))
            {
                Install-Module -Name MicrosoftTeams -Force 
            }
            else 
            {
                throw "MicrosoftTeams module required for function. Exiting."
            }
        }

        # Check if connected to Microsoft Teams, connect if not
        try
        {
            Get-CsTenant > $null 
        }
        catch 
        {
            Write-Verbose "Connecting to Microsoft 365"
            Connect-MicrosoftTeams 
        }
    }
    
    PROCESS
    {
        # Retrieve all teams' group IDs and then get users for each group
        (Get-Team).GroupId | ForEach-Object {
            Get-TeamUser -GroupId $_
        } | Sort-Object user -Unique     
    }
}