'How to Get Azure AD Object by Object ID Using Azure CLI
In the Azure Portal, one can look-up an Azure AD object based on the Object ID as shown below:
Is it possible to retrieve an Azure AD object by the Object ID using the Azure CLI?
In order to use the Azure CLI to get the object related to the object ID, it appears that I need to know in advance if the related resource is a user, group, device, app registration, etc., in order to get the details. For example, if I know the Object ID is a user, I can use az ad user show --id
. If all I have is the Object ID, I don't know the 'type' of the object, yet somehow the Portal can figure this out!
While I'd prefer an Azure CLI solution, an Azure PowerShell solution would be better than nothing. I am asking the question because I'm trying to generate a list of access policies within key vault using az keyvault list
, but the access policy list from that CLI command just shows Object IDs for each policy... I have no way of determining if the objects are users, groups, etc.
Solution 1:[1]
If you want to get Azure AD resource with its object id, we can use the following Microsoft Graph API
POST https://graph.microsoft.com/v1.0/directoryObjects/getByIds
Content-type: application/json
{
"ids":[""]
}
If you want to call the Microsoft Graph with Azure CLI, we can use the command az rest
For example (I use Azure cloud shell)
az rest --method POST --url 'https://graph.microsoft.com/v1.0/directoryObjects/getByIds' --headers 'Content-Type=application/json' --body '{"ids":[""]}'
Solution 2:[2]
If you have a CSV file with user IDs in one column, this script is useful to look up all users at once
param(
$file = "query_data.csv"
)
$data = Get-Content $file | ConvertFrom-Csv
$userIds = $data.User | Get-Unique
$body = @{
ids = $userIds
} | ConvertTo-Json -Compress;
$body = $body -replace '"', '\"';
$results = az rest `
--method POST `
--url 'https://graph.microsoft.com/v1.0/directoryObjects/getByIds' `
--headers 'Content-Type=application/json' `
--body $body;
$results > results.json
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jim Xu |
Solution 2 | TeamDman |