Azure Automation PowerShell脚本认证问题:Connect-AzureAD报错求助
问题描述
在Azure Automation中部署管理External Identities的PowerShell查询,已配置系统托管标识并通过Connect-AzAccount -Identity成功连接,但执行Get-AzureADPolicy时提示:
You must call the Connect-AzureAD cmdlet before calling any other cmdlets
尝试通过Az上下文连接AzureAD的代码:
$AzureContext = Set-AzContext -SubscriptionName $AzureContext.Subscription -DefaultProfile $AzureContext -ErrorAction Stop Connect-AzureAD -TenantId $AzureContext.Tenant.TenantId -AccountId $AzureContext.Account.Id
之后出现错误:
Unable to find an entry point named 'GetPerAdapterInfo' in DLL 'iphlpapi.dll'
解决方案
1. 用托管标识令牌连接AzureAD(规避模块兼容问题)
不要通过Az上下文的AccountId连接,直接获取托管标识的Azure AD访问令牌来认证:
# 获取Azure AD资源的访问令牌 $aadToken = (Get-AzAccessToken -ResourceUrl "https://graph.windows.net").Token $tenantId = (Get-AzContext).Tenant.Id # 使用令牌连接AzureAD Connect-AzureAD -AadAccessToken $aadToken -AccountId "system" -TenantId $tenantId # 执行查询 Get-AzureADPolicy
2. 升级/替换AzureAD模块
iphlpapi.dll的错误通常源于AzureAD模块与Azure Automation运行环境不兼容:
- 在Azure Automation账户的「模块」页面,检查AzureAD模块版本,升级至最新稳定版;
- 推荐改用Microsoft Graph模块(AzureAD模块已被弃用),步骤如下:
- 在Automation账户中导入
Microsoft.Graph.Identity.SignIns模块; - 给系统托管标识授予Microsoft Graph的
Policy.Read.All(或对应所需)应用权限; - 使用以下代码执行查询:
# 通过托管标识连接Microsoft Graph Connect-MgGraph -Identity # 获取策略(对应Get-AzureADPolicy的Graph命令) Get-MgPolicy - 在Automation账户中导入
3. 确认托管标识权限
确保系统托管标识在Azure AD中拥有足够权限:
- 进入Azure AD的「企业应用」,找到对应Automation账户的托管标识;
- 切换至「权限」页面,添加并授予所需的Azure AD或Microsoft Graph权限(如读取策略的权限)。
内容的提问来源于stack exchange,提问作者JohnD
相关产品推荐
相关产品推荐

