如何使用 Azure CLI 通过对象 ID 获取 Azure AD 对象

How to Get Azure AD Object by Object ID Using Azure CLI

在 Azure 门户中,可以根据对象 ID 查找 Azure AD 对象,如下所示:

是否可以使用 Azure CLI 通过对象 ID 检索 Azure AD 对象?

为了使用Azure CLI获取与对象ID相关的对象,看来我需要提前知道相关资源是用户、组、设备、应用程序注册等,在以获取详细信息。例如,如果我知道对象 ID 是用户,我可以使用 az ad user show --id。如果我只有对象 ID,我不知道对象的 'type',但 Portal 可以以某种方式解决这个问题!

虽然我更喜欢 Azure CLI 解决方案,但 Azure PowerShell 解决方案总比没有好。我问这个问题是因为我正在尝试使用 az keyvault list 在密钥保管库中生成访问策略列表,但是该 CLI 命令的访问策略列表只显示每个策略的对象 ID...我没办法确定对象是用户、组等

如果你想获取 Azure AD 资源及其对象 ID,我们可以使用以下 Microsoft Graph API

POST https://graph.microsoft.com/v1.0/directoryObjects/getByIds
Content-type: application/json

{
    "ids":[""]
}

如果你想用Azure CLI调用Microsoft Graph,我们可以使用命令az rest

例如(我用Azure cloud shell

az rest --method POST --url 'https://graph.microsoft.com/v1.0/directoryObjects/getByIds' --headers 'Content-Type=application/json'  --body '{"ids":[""]}'

详情请参考here nad here

如果您有一个 CSV 文件,其中一列包含用户 ID,此脚本可用于一次查找所有用户

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