Search code examples
azurepowershellmicrosoft-graph-api

Powershell, Tying 2 variables together in one script


I have the following script. It is getting me a system array. I need to tie the $id variable and the $upn variable together with each iteration. I am at a loss on how to get the loop to continue through and tie the 2 variables together. Any help would be appreciated.

$adroles = get-mgdirectoryrole | select displayname,Id
$upn = foreach ($id in $adroles.id) { 
    Get-mgdirectoryrolemember -DirectoryRoleId $id | 
        select-object -expandproperty additionalproperties |
            foreach-object -membername userPrincipalName
}
}


Solution

  • I believe you're looking to merge the output from Get-MgDirectoryRole with the output from Get-MgDirectoryRoleMember, if that's the case this is how you can do it:

    Get-MgDirectoryRole | ForEach-Object {
        foreach($upn in (Get-MgDirectoryRoleMember -DirectoryRoleId $_.Id).additionalProperties.userPrincipalName) {
            [pscustomobject]@{
                DisplayName       = $_.DisplayName
                Id                = $_.Id
                UserPrincipalName = $upn
            }
        }
    }
    

    There is another way to get this information in a single API call by using the $expand parameter on the members relationship:

    $uri = 'v1.0/directoryRoles?$expand=members&$select=displayName'
    
    do {
        $response = Invoke-MgGraphRequest GET $uri
        $uri = $response.'@odata.nextLink'
    
        foreach ($role in $response.value) {
            foreach ($member in $role.members) {
                [pscustomobject]@{
                    RoleId                  = $role['id']
                    RoleDisplayName         = $role['displayName']
                    MemberUserPrincipalName = $member['userPrincipalName']
                    MemberDisplayName       = $member['displayName']
                    MemberType              = $member['@odata.type'].Split('.')[-1]
                }
            }
        }
    }
    while ($uri)