Azure Automation中Connect-MgGraph因Newtonsoft.Json缺失报错求助
背景
我正忙于将Azure AD PowerShell脚本迁移至Microsoft Graph PowerShell,已准备好部分要在Azure Automation中运行的脚本,但尚未理清如何完成连接。此前使用Azure AD PowerShell时,我在Azure Automation中配置了关联服务账户;现在尝试使用Microsoft Graph PowerShell时,打算借助Azure Automation账户中的RunAs账户进行连接。
所用连接代码
$Connection = Get-AutomationConnection -Name AzureRunAsConnection # Get certificate from the automation account $Certificate = Get-AutomationCertificate -Name AzureRunAsCertificate # Connect to the Graph SDK endpoint using the automation account Connect-MgGraph -ClientID $Connection.ApplicationId -TenantId $Connection.TenantId -CertificateThumbprint $Connection.CertificateThumbprint
运行错误信息
Connect-MgGraph: C:\Temp\os4k24vd.4cs\xxxxxxxxxxxxxxxxxxx.ps1:5 Line | 5 | Connect-MgGraph -ClientID $Connection.ApplicationId -TenantId $Connec … | ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ | Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, | Culture=neutral, PublicKeyToken=xxxxxxx'. The system cannot find the file specified.
已做操作
已安装了Connect-MgGraph所需的Microsoft.Graph.Authentication模块(Runtime版本7.1),查询得知该错误与.NET无法找到Json.NET库有关。
求助问题
想请教Azure Automation中缺少哪个模块,或是否有其他方式连接Microsoft Graph PowerShell与Azure Automation?
1. 安装缺失的Newtonsoft.Json模块
Azure Automation默认未包含Microsoft.Graph.Authentication依赖的13.0.0.0版本Newtonsoft.Json,需手动导入:
- 登录Azure门户,进入目标Automation账户
- 左侧菜单选「模块」>「添加模块」
- 从PowerShell Gallery搜索
Newtonsoft.Json,选择13.x版本导入 - 等待模块导入完成后重新运行RunBook
2. 改用Managed Identity连接(更推荐)
无需处理依赖问题,直接用Automation账户的系统分配托管身份连接:
- 在Automation账户的「标识」选项卡,启用系统分配托管身份
- 在Azure AD中为该托管身份分配所需的Microsoft Graph权限(如
User.Read.All,根据脚本需求选择) - 修改RunBook连接代码为:
Connect-MgGraph -Identity
这种方式无需证书、ClientID,避免依赖缺失问题,且更安全简洁。
3. 确认模块版本兼容性
确保安装的Microsoft.Graph.Authentication模块与Azure Automation的PowerShell Runtime 7.1兼容,建议安装该模块的最新稳定版,避免版本不匹配引发的依赖问题。
内容的提问来源于stack exchange,提问作者user16113972

