Get-TeamsUserAppPermissionPolicyAssignment.psm1

function Get-TeamsUserAppPermissionPolicyAssignment
{
    <#
    .SYNOPSIS
    Retrieves custom Application Permission Policies and their associated users.
 
    .DESCRIPTION
    This function retrieves a list of custom Application Permission Policies assigned to users in Microsoft Teams.
 
    .NOTES
    Author: Eric Meinders
    Version: 1.0
    #>


    [alias("Get-AppPermissionAssignment")]
    [cmdletbinding(SupportsShouldProcess, ConfirmImpact = "High")]
    param()

    # Check if the MicrosoftTeams module is installed, install if not
    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 
    }

    # Retrieve all unique users from Teams groups
    $allUsers = (Get-Team).GroupId | ForEach-Object {
        (Get-TeamUser -GroupId $_).User
    } | Sort-Object -Unique
    
    $i = 1
    foreach ($user in $allUsers)
    {
        # Display progress for each user
        Write-Progress -Id 1 -Activity "User: ${user}" -Status "${i} of $($allUsers.Count)" -PercentComplete (($i / $allUsers.Count) * 100)
        
        # Retrieve policy assignment for user
        $policyAssignment = Get-CsUserPolicyAssignment -Identity $user | Where-Object {
            $_.PolicyType -eq "TeamsAppPermissionPolicy"
        }
        $i++

        # Create custom objects for each policy assignment
        $policyAssignment | ForEach-Object {
            [PSCustomObject]@{
                User = $user
                AppPermissionPolicy = $_.PolicyName
            }
        }
    }
}