Forum Discussion
ktc2
Feb 21, 2025Copper Contributor
A little help please with Get-AzADObject
I am trying to write a PowerShell script that will list the users who hold specified Azure roles into a .csv file for security reviews. I'm new to PowerShell and I'm struggling with this for far too ...
AP_TC_ECASD
Feb 23, 2025Copper Contributor
It looks like you're mixing AzureAD and Az PowerShell modules, which are separate. Get-AzADObject is not a valid cmdlet in the Az module. Instead, use Get-AzADUser for users and Get-AzADGroup for groups.
Here’s a corrected version of your script:
Fixed Issues:
- Incorrect Cmdlet: Get-AzADObject doesn’t exist. Instead:
- Use Get-AzADUser for users.
- Use Get-AzADGroup for groups.
- Missing Scope in Loop: The foreach loop for $roleAssignments wasn’t properly enclosed.
- Fixing ObjectType Handling: Since the PrincipalId could belong to a user or group, we check its type.
Corrected PowerShell Script:
# Connect to Azure
Connect-AzAccount
# Define the Azure roles to check
$roles = "Owner", "Contributor", "Storage Blob Data Contributor"
# Create an empty array to store the results
$results = @()
# Loop through each role
foreach ($role in $roles) {
# Get role assignments for the current role
$roleAssignments = Get-AzRoleAssignment -RoleDefinitionName $role
# Loop through each role assignment
foreach ($assignment in $roleAssignments) {
$principalId = $assignment.PrincipalId
# Try to get the user first
$principal = Get-AzADUser -ObjectId $principalId -ErrorAction SilentlyContinue
# If not a user, check if it's a group
if (-not $principal) {
$principal = Get-AzADGroup -ObjectId $principalId -ErrorAction SilentlyContinue
}
# If we found a principal, add to results
if ($principal) {
$result = [PSCustomObject]@{
Role = $role
DisplayName = $principal.DisplayName
UserPrincipalName = if ($principal.UserPrincipalName) { $principal.UserPrincipalName } else { "N/A" }
ObjectType = if ($principal.ObjectType) { $principal.ObjectType } else { "Unknown" }
}
# Add the result to the array
$results += $result
}
}
}
# Export the results to a CSV file
$results | Export-Csv -Path "C:\Temp\AzureRoleUsers.csv" -NoTypeInformation
Write-Output "Export complete. File saved at C:\Temp\AzureRoleUsers.csv"
Key Fixes:
✅ Uses Get-AzADUser instead of Get-AzADObject
✅ Handles both users and groups correctly
✅ Adds error handling (-ErrorAction SilentlyContinue) to avoid failures
✅ Ensures $roleAssignments is correctly looped over
This should now work for your security reviews. Let me know if you run into any issues! 🚀