Azure AD – export groups and members #2

Due to the popularity of the initial script (cheers!) Azure AD – Export Groups and Members to CSV, and thanks to David for asking, this script will export the groups and the members with properties ObjectID, UserPrincipalName and Email Address. This one uses the AzAD cmdlets. To import them, use:

Install-Module Az -SkipPublisherCheck -Force -AllowClobber -Confirm:$false

Enjoy! 🍻🤟🙂🤟🍻


$allgroups = Get-AzADGroup

$result = foreach ( $group in $allgroups ) {

    $hash = @{
        GroupName=$group.DisplayName
        Member=''
        Email=''
        UserPrincipalName=''
        ObjectId=''
    }
    
    $groupid = $group.id
    $groupdisplayname = $group.DisplayName

        if ( $members = Get-AzADGroupMember -GroupObjectId $groupid ) {

            foreach ( $member in $members ) {

                $objectid = $member.Id
                $userinfo = Get-AzADUser -ObjectId $objectid
                $displayname = $userinfo.DisplayName
                $email = $userinfo.Mail
                $upn = $userinfo.UserPrincipalName

        $hash.member = $displayname
        $hash.email = $email
        $hash.userprincipalname = $upn
        $hash.objectid = $objectid
        New-Object psObject -Property $hash

}
}
}

$result | Export-Csv -Path c:\temp\aadgroupsandmembers.csv -NoTypeInformation