合并Get-AzureADUser多管道查询:获取同步成员与许可证状态
合并Entra ID用户查询与许可证状态获取的PowerShell方案
要减少Azure数据调用次数,核心是通过单次Microsoft Graph API请求同时获取用户基本信息和许可证分配数据,避免先查用户再逐个调取许可证的低效模式。以下是具体实现方案:
前提准备
确保已安装并连接Microsoft Graph PowerShell模块(AzureAD模块已弃用,推荐使用Graph模块):
Install-Module Microsoft.Graph.Users -Force Connect-MgGraph -Scopes User.Read.All, Organization.Read.All
基础合并查询(一次API调用)
直接在用户查询中指定返回许可证属性,无需二次调用:
Get-MgUser -Filter "userType eq 'Member' and dirSyncEnabled eq true" ` -Property Id, DisplayName, UserPrincipalName, UserType, DirSyncEnabled, AssignedLicenses ` | Select-Object Id, DisplayName, UserPrincipalName, UserType, DirSyncEnabled, @{Name='LicenseStatus'; Expression={ # 判断用户是否有分配的许可证 if ($_.AssignedLicenses.Count -gt 0) { 'Licensed' } else { 'Unlicensed' } }}, @{Name='AssignedSkuIds'; Expression={ # 列出所有分配的许可证SkuId $_.AssignedLicenses.SkuId -join ', ' }}
关键说明
-Filter参数:直接在API层面筛选符合条件的用户,减少返回的数据量和本地处理压力。-Property参数:明确指定包含AssignedLicenses,让Graph API一次性返回用户基本信息和许可证数据,彻底避免多次调用。- 计算属性:通过
Select-Object的自定义表达式生成可读性更高的LicenseStatus和AssignedSkuIds字段。
进阶:显示具体许可证名称
如果需要显示许可证的具体名称(而非SkuId),可先获取租户内的SKU映射表(仅需一次调用),再匹配用户的许可证:
# 一次性获取租户所有可用SKU信息 $skuMap = Get-MgSubscribedSku | Select-Object SkuId, SkuPartNumber # 查询用户并匹配许可证名称 Get-MgUser -Filter "userType eq 'Member' and dirSyncEnabled eq true" ` -Property Id, DisplayName, UserPrincipalName, UserType, DirSyncEnabled, AssignedLicenses ` | Select-Object Id, DisplayName, UserPrincipalName, UserType, DirSyncEnabled, @{Name='LicenseStatus'; Expression={ if ($_.AssignedLicenses.Count -gt 0) { 'Licensed' } else { 'Unlicensed' } }}, @{Name='AssignedLicenses'; Expression={ $_.AssignedLicenses.SkuId | ForEach-Object { $sku = $skuMap | Where-Object { $_.SkuId -eq $_ } $sku.SkuPartNumber } -join ', ' }}
为什么之前的方法失败?
- 直接拼接管道:如果使用
Get-MgUser | Get-MgUserLicenseDetail,会对每个用户发起一次独立API请求,不仅效率低,且默认Get-MgUser不会返回AssignedLicenses属性,后续处理无数据可用。 - Add-Member无效:若未在初始查询中获取
AssignedLicenses,后续通过Add-Member添加的属性会因无数据源而无法填充正确值。
内容的提问来源于stack exchange,提问作者Makke_
相关产品推荐
相关产品推荐

