12

In the Azure Portal, one can look-up an Azure AD object based on the Object ID as shown below:

enter image description here

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.

enter image description here

PoorInRichfield
  • 1,436
  • 2
  • 19
  • 29

2 Answers2

19

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\":[\"\"]}'

enter image description here

For more details, please refer to here nad here

Jonathan Sayce
  • 9,359
  • 5
  • 37
  • 51
Jim Xu
  • 21,610
  • 2
  • 19
  • 39
  • 5
    Thank you. Note that the `--body` string has to have the quotes escaped or else the call fails. For example: `--body '{\"ids\":[\"087f593b-bedf-44d4-8732-96ab980f2b45\"]}'` Looks like there's no way to make this same call using a local instance of PowerShell? I.e., not using Azure Cloud Shell? I find Azure cloud shell rather inconvenient to work with for writing long scripts. – PoorInRichfield Jun 14 '21 at 12:54
  • This seems to work using the Azure CLI locally as well... i.e., not in Azure Cloud Shell. – PoorInRichfield Jun 14 '21 at 13:03
0

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
TeamDman
  • 649
  • 6
  • 26