Search for users in Azure AD with PowerShell who have a directory role assigned!

MVP

 

Hi Azure friends,

 

It was about a following customer scenario. The task was to search for users who have been assigned a directory role in Azure Active Directory. Of course this search can be done with the Azure Portal. However, I think we can agree that this might take a bit of time. Let's work together with PowerShell.

 

I used the PowerShell ISE for this configuration. But you are also very welcome to use Visual Studio Code, just as you wish. Please start with the following steps to begin the deployment (the Hashtags are comments):

 

#The first two lines have nothing to do with the configuration, but make some space below in the blue part of the ISE.

Set-Location C:\
Clear-Host

 

#We need the cmdlets
Install-Module -Name AzureAD -AllowClobber -Force -Verbose

 

#Sometimes the module must be imported
Import-Module AzureAD

 

#Let's connect
Connect-AzureAD

 

#To explore the available cmdlets in the Azure AD module
Get-Command -Module AzureAD | Measure-Object

 

#Fetch list of all directory roles with object ID
Get-AzureADDirectoryRole

 

#Fetch a specific directory role by ID
$role = Get-AzureADDirectoryRole -ObjectId "6fd5c3ac-2e62-4fca-84fe-9e32ae5282f2"

 

#Fetch role membership for a role (to get an idee)
Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId | Get-AzureADUser

 

#Lets create some variables
$roleUsers = @()
$roles=Get-AzureADDirectoryRole

 

#We use a loop
ForEach($role in $roles) {
$users=Get-AzureADDirectoryRoleMember -ObjectId $role.ObjectId
ForEach($user in $users) {
write-host $role.DisplayName,$user.DisplayName,$user.UsageLocation
$obj = New-Object PSCustomObject
$obj | Add-Member -type NoteProperty -name RoleName -value ""
$obj | Add-Member -type NoteProperty -name UserDisplayName -value ""
$obj | Add-Member -type NoteProperty -name UsageLocation -value ""
$obj.RoleName=$role.DisplayName
$obj.UserDisplayName=$user.DisplayName
$obj.UsageLocation=$user.UsageLocation
$roleUsers+=$obj
}
}

 

#We have a result
$roleUsers

 

#A bit more readable
$roleUsers | Sort-Object Userdisplayname | select Userdisplayname, RoleName

 

#Remove the session
Disconnect-AzureAD

 

Now we have a listing of users who have been given a directory role in Azure AD. I know that wasn't super fancy at all. But I really wanted to share my experience with you.

 

I hope this article was useful. Best regards, Tom Wechsler

 

P.S. All scripts (#PowerShell, Azure CLI, #Terraform, #ARM, etc.) that I use can be found on github! https://github.com/tomwechsler

3 Replies
Thank you for sharing. Handy to have, particularly for Governance and auditing purposes!

But does this give eligible role assignment details? I guess it returns active role assignments.

rahulraj40_0-1668435236101.png