Get a list of all groups in Azure for al members with a specific company

Viewed 58

I need just a list of all groups (just the group names and desciption, not the users) that anyone who part of Company A (field in AD) is part of the company. This is what I have, but can't get it to work right. Any help?

$UserList = @()
$FinalGroupList = @()
$UserList = Get-Recipient -Filter {Company -eq "Company"} | where-object {$_.RecipientType -eq "UserMailbox"}


foreach ($user in $UserList) {
    $CurrentUserGroups = Get-AzureADUser -User $user.PrimarySmtpAddress | Get-AzureADUserMembership
    foreach ($group in $CurrentUserGroups) {
        if ($FinalGroupList.displayname -notcontains $group.displayname) {
            $FinalGroupList = $FinalGroupList + $group
        }
    }
}

foreach ($FinalListItem in $FinalGroupList) {
    $CSVData = New-Object psobject
    $CSVData | Add-Member -MemberType NoteProperty -name DisplayName -Value $FinalListItem.DisplayName
    $CSVData | Add-Member -MemberType NoteProperty -name Description -Value $FinalListItem.Description
    $CSVData | export-csv c:\temp\Groups.csv -Append -NoTypeInformation
}
1 Answers

I have tried in my environment with below powershell commands to get the group and its description whose users are present in specific company and could successfully get the same.

#Get-AzureADUser -All $true | Select-Object -Property CompanyName, UserPrincipalName
#$companyUsers =Get-AzureADUser | ?{ $_.CompanyName -eq '<that specific company name>' }

$companyname=”SamComp”  //this the specific company name I  am looking for
$companyUsers =Get-AzureADUser | ?{ $_.CompanyName -eq 'SamComp' }

foreach ($user in $companyUsers) {
Get-AzureADUserMembership  -ObjectId $user.ObjectId
$groups = $user | Get-AzureADUserMembership

$list | Sort-Object DisplayName -Unique | fl -GroupBy DisplayName -Property Description 

$list
}

OUTPUT:

enter image description here

Reference: Get-AzureADUserMembership (AzureAD) | Microsoft Docs

Related