Functions/Find-AADGroupmembership.ps1


function Find-AADGroupmembership {

    param (
        [parameter(mandatory = $false)] [string] $AADGroup,
        [parameter(mandatory = $false)] [string] $Member,
        [parameter()] [switch] $MoreInfo
    )

    if ((!$Member) -and (!$AADGroup)) {
        break
    }

    $Result = @()

    Get-AzureADGroup -All $true -SearchString $AADGroup | Sort-Object DisplayName | ForEach-Object {

        $AADGroupMembers = Get-AzureADGroupMember -ObjectId $_.ObjectId -All $true | Where-Object { ($_.DisplayName -like "*$Member*") -or ($_.UserPrincipalName -like "*$Member*") }
        if ($AADGroupMembers) {
            # $_.DisplayName
            # $AADGroupMembers | Sort-Object DisplayName | Format-Table -AutoSize
            # Write-Output "--"
            foreach ($a in $AADGroupMembers) {

                $obj = [ordered]@{
                    DeviceName = $a.DisplayName
                    GroupName  = $_.DisplayName
                }
                if ($MoreInfo) {
                    $obj.Add("GroupID", $_.ObjectId)
                    $obj.Add("ObjectId", $a.ObjectId)
                    $obj.Add("DeviceId", $a.DeviceId)
                }
                $Result += New-Object -TypeName psobject -Property $obj
            }
        }
    }

    $Result = $Result | Sort-Object DeviceName
    return $Result # | Format-Table

}