Hello Community,
I'm facing an issue with retrieving the "department" attribute from the Microsoft Graph API. I've been trying to develop a PowerShell script for Azure Automation that assigns users to groups based on their department, but I'm not able to retrieve the department value successfully.
Here are the details:
- I have set up an Azure AD app registration with the necessary permissions for Microsoft Graph API access.
- I'm using PowerShell to authenticate and make requests to the API.
- I'm able to retrieve user data using the API, but the "department" attribute is consistently missing from the response.
I've tried the following steps to troubleshoot:
- Adjusting Filters: I've adjusted the filters to ensure that the users I'm trying to retrieve have the necessary attributes. The department values are not null or empty in Azure AD.
- Debugging: I added debugging prints to see the full user data retrieved from the API, and the "department" attribute is not present in the response.
- Check Permissions: I've double-checked the permissions for the app registration and granted admin consent for User.Read.All.
I'm at a loss as to why I can't retrieve the "department" attribute despite following the correct procedures. Has anyone encountered a similar issue or can provide insights into what might be causing this?
Please also review the attached PowerShell script and let me know if any changes are required. However, when I tried Same URI mentioned in the script with Microsoft Graph Explorer it works!
Any guidance or suggestions would be greatly appreciated. Thank you in advance!
# Variables
$tenantId = "------------------------"
$appId = "--------------------------"
$appSecret = "-----------------------"
$startDate = (Get-Date).AddDays(-15).ToString("yyyy-MM-ddTHH:mm:ssZ")
$body = @{
grant_type = "client_credentials"
client_id = $appId
client_secret = $appSecret
resource = "https://graph.microsoft.com"
}
$response = Invoke-RestMethod -Uri $tokenUrl -Method Post -ContentType "application/x-www-form-urlencoded" -Body
$body$token = $response.access_token
$usersUrl = "https://graph.microsoft.com/v1.0/users?$filter=userType eq 'Member' and employeeId ge ' ' and accountEnabled eq true and creationDataTime eq $startdate&$select=displayName,userPrincipalName,id,department"
$headers = @{ Authorization = "Bearer $token"}
$userResponse = Invoke-RestMethod -Uri $usersUrl -Headers $headers -Method Get -ContentType "application/x-www-form-urlencoded"
$users = $userResponse.value
foreach ($user in $users) {
Write-Output "Processing user:$($user.displayName) - UPN: $($user.userPrincipalName)- Department: $($user.department)"
}
Regards
Dhruvin