You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用服务主体连接Azure AD时Get-AzureADUser报错问题排查

问题原因与解决方法

你的问题出在Az模块和AzureAD模块的身份认证上下文不共享:Connect-AzAccount是给Az系列命令用的登录,而Get-AzureADUser属于AzureAD模块的命令,两者的认证会话完全独立,所以你试图用Az的上下文去登录AzureAD的方式无效,依然会触发交互式登录弹窗。

正确的服务主体登录AzureAD方式

直接用Connect-AzureAD的服务主体专属登录参数,不需要依赖Az模块的上下文。具体操作如下:

  1. 确保已安装AzureAD模块(未安装的话先执行:Install-Module -Name AzureAD -Force -AllowClobber)
  2. 替换脚本中的登录逻辑,用服务主体直接完成AzureAD模块的认证

修正后的完整脚本

# 导入所需模块
Import-Module Az
Import-Module AzureAD

# 服务主体核心信息
$tenantId = "xxxxxxx"
$clientId = "xxxxxxx"
$clientSecret = "xxxxxxxxx"

# 转换密钥为安全格式
$secureClientSecret = ConvertTo-SecureString $clientSecret -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($clientId, $secureClientSecret)

# 登录Az模块(后续不需要Az命令的话可删除此行)
Connect-AzAccount -ServicePrincipal -TenantId $tenantId -Credential $credential

# 关键:用服务主体登录AzureAD模块
Connect-AzureAD -TenantId $tenantId -Credential $credential -ServicePrincipal

# 定义要筛选的公司名称
$companyName = "some company"

# 获取并筛选目标用户
$users = Get-AzureADUser -All $true | Where-Object {
    $_.CompanyName -eq $companyName -and $_.JobTitle -ne $null
} | Select-Object DisplayName, JobTitle, Mail, Department

# 导出结果到CSV文件
$users | Export-Csv -Path "c:\temp\Users.csv" -NoTypeInformation

额外注意事项

  • 你的服务主体必须配置Azure AD目录读取权限(比如Directory.Read.All应用权限),否则Get-AzureADUser会返回权限不足的错误
  • 如果使用AzureADPreview模块,只需将Import-Module AzureAD替换为Import-Module AzureADPreview即可,其余语法一致

内容的提问来源于stack exchange,提问作者Asthika Welikala

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.20 09:11:10