Home > Mobile >  View groups for every user in Azure AD with powershell
View groups for every user in Azure AD with powershell

Time:10-15

As the title said. im looking for a way to list every user, with the group(s), they are in.

I'm aware of how you could use Get-AzureADGroupMember -ObjectId "groupidhere" and then the output is all the users in that group. but how would you automate this? is this even possible to do with powershell?

after this ill be using this table to create a table in Hudu. i havent seen anyone do this with groups and users together though, so for all i know its not possible or supposed to be.

So the output i get here from $Users to also show some of the output from $Groups_Name

A table where i have all the info about a user, but also what groups they are in.

| Name | Email | Group |

so the output would be something like this:

DisplayName     UserPrincipalName     DisplayName
-----------     -----------------     -----------
Name Nameson     user@domain.com       Group names 
Name Nameson     user@domain.com       Group names
Name Nameson     user@domain.com       Group names
Name Nameson     user@domain.com       Group names
Name Nameson     user@domain.com       Group names
Name Nameson     user@domain.com       Group names
Name Nameson     user@domain.com       Group names
Name Nameson     user@domain.com       Group names

Script im working on (i know this is super messy)

# Table of all users
$Users = Get-AzureADUser -All:$true

# Table of all groups
$Groups = Get-AzureADGroup


# ALL users ObjectId
$Users_ObjectId = $Users | Select-Object ObjectId

# ALL Groups ObjectId
$Groups_ObjectId = $Groups | Select-Object ObjectId

#Group names - list
$Groups_Name = $Groups | Select-Object DisplayName

#User names - list
$Users_Name = $Users | Select-Object DisplayName

foreach ($i in $Users ) {

    # If
    if ($Groups -contains $Users_ObjectId) {

        #print a table with desired formatting
        #$Users $Groups_Name 
    }
}

CodePudding user response:

Try using Get-AzureADUserMembership like this:

$users = Get-AzureADUser -All $true

$report = Foreach ($user in $users) {
  $groups = $user | Get-AzureADUserMembership

  # create output objects with username and groups:
  Foreach ($group in $groups) {
    [PSCustomObject][ordered]@{ 
      UserDisplayName   = $user.DisplayName
      UserPrincipalName = $user.UserPrincipalName
      GroupDisplayName  = $group.DisplayName
}}}

# print a table with desired formatting
$report | ft

And the report looks like so:

UserDisplayName UserPrincipalName  GroupDisplayName                            
--------------- -----------------  ----------------                            
John Smith      j.smith@domain.com Marketing
John Smith      j.smith@domain.com Marketing-VIPs
John Doe        j.doe@domain.com   Sales                           
John Doe        j.doe@domain.com   Management  
  • Related