Elly
Elly

Reputation: 55

View groups for every user in Azure AD with powershell

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     [email protected]       Group names 
Name Nameson     [email protected]       Group names
Name Nameson     [email protected]       Group names
Name Nameson     [email protected]       Group names
Name Nameson     [email protected]       Group names
Name Nameson     [email protected]       Group names
Name Nameson     [email protected]       Group names
Name Nameson     [email protected]       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 
    }
}

Upvotes: 0

Views: 3577

Answers (1)

Cpt.Whale
Cpt.Whale

Reputation: 5321

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      [email protected] Marketing
John Smith      [email protected] Marketing-VIPs
John Doe        [email protected]   Sales                           
John Doe        [email protected]   Management  

Upvotes: 1

Related Questions