Getting hashtable in for each loop

HI there, I m trying to get list of AZURE privilage Groups, their members and other group properties.
I use below script, but when I check $properties variable, it store only one entry.
#Getting list of AZURE RoleGroups
$RoleGroups = Get-AzureADMSPrivilegedResource -ProviderId “aadGroups”

$Assignment = @()

foreach($g in $RoleGroups){
$Assignment += Get-AzureADMSPrivilegedRoleAssignment -ProviderId “aadGroups” -ResourceId $g.id
}

$result = @()
foreach($c in $Assignment){

$properties = @{GroupName = ‘(Get-AzureADGroup -ObjectId $c.ResourceId).DisplayName’
AdminName = (Get-AzureADUser -ObjectId $c.SubjectId ).UserPrincipalName
Assignment = $c.AssignmentState
MemberType = $c.MemberType
StartDate = $c.StartDateTime
EndDate = $c.EndDateTime
}

}

My proble is that script runs OK but when I run $properties it has only one entry in it.
Many thanks for the help
Sa

Saeed,
Welcome to the forum. :wave:t4:

When you post code, sample data, console output or error messages please format it as code using the preformatted text button ( </> ). Simply place your cursor on an empty line, click the button and paste your code.

Thanks in advance

How to format code in PowerShell.org <---- Click :point_up_2:t4: :wink:

You overwrite the variable $properties in each loop iteration. That’s why you only have the last one in it when you finish the loop.

This should do the trick:

$RoleGroups = Get-AzureADMSPrivilegedResource -ProviderId 'aadGroups'

$Assignment =
foreach ($g in $RoleGroups) {
    Get-AzureADMSPrivilegedRoleAssignment -ProviderId 'aadGroups' -ResourceId $g.id
}

$result = 
foreach ($c in $Assignment) {
    [PSCustomObject]@{
        GroupName  = (Get-AzureADGroup -ObjectId $c.ResourceId).DisplayName
        AdminName  = (Get-AzureADUser -ObjectId $c.SubjectId ).UserPrincipalName
        Assignment = $c.AssignmentState
        MemberType = $c.MemberType
        StartDate  = $c.StartDateTime
        EndDate    = $c.EndDateTime
    }
}

$result 
1 Like

Such a fabulous forum. Many thanks Olaf, worked like a charm. Greatly apprecate your help.
Best regards
Sa