求助:基于PowerShell与Graph API将Entra用户许可证信息存入PSCustomObject
解决方案:批量获取Microsoft Entra用户及已分配许可证并整合为自定义对象
以下是实现需求的完整PowerShell代码,包含批量处理、分页兼容和边界情况处理:
# 确保已完成身份验证,例如通过Connect-MgGraph或手动获取访问令牌 # $Headers = @{ Authorization = "Bearer $accessToken" } # 1. 获取所有用户(处理Graph API分页,避免遗漏数据) $allUsers = @() $getUsersUrl = "https://graph.microsoft.com/v1.0/users" do { $response = Invoke-RestMethod -Uri $getUsersUrl -Headers $Headers -Method Get $allUsers += $response.Value | Select-Object DisplayName, UserPrincipalName, Id $getUsersUrl = $response.'@odata.nextLink' } while ($getUsersUrl) # 2. 遍历用户,查询许可证并整合信息 $userLicenseResults = @() foreach ($user in $allUsers) { $licenseUrl = "https://graph.microsoft.com/v1.0/users/$($user.Id)/licenseDetails" try { $licenseResponse = Invoke-RestMethod -Uri $licenseUrl -Headers $Headers -Method Get # 拼接多个许可证为字符串,无许可证时标记为"无" $assignedLicenses = if ($licenseResponse.Value) { $licenseResponse.Value.skuPartNumber -join ', ' } else { "无" } } catch { # 处理查询失败场景(如权限不足、用户不存在) $assignedLicenses = "查询失败: $($_.Exception.Message)" } # 构建自定义对象,整合用户与许可证信息 $userLicenseObject = [PSCustomObject]@{ DisplayName = $user.DisplayName UserPrincipalName = $user.UserPrincipalName UserId = $user.Id AssignedLicenses = $assignedLicenses } $userLicenseResults += $userLicenseObject } # 输出最终结果 $userLicenseResults
关键细节说明
- 分页处理:Graph API默认单次返回100条数据,通过
@odata.nextLink循环拉取所有用户,避免遗漏。 - 许可证信息处理:将多个许可证的
skuPartNumber拼接为易读字符串,同时处理无许可证、查询失败的边界情况。 - 自定义对象构建:通过
[PSCustomObject]将用户基础信息与许可证数据整合,统一存储和输出格式。
注意事项
- API版本:优先使用稳定的
v1.0版本API,避免依赖beta版本的变动特性。 - 速率限制:若用户数量较多,建议在循环中添加
Start-Sleep -Seconds 1,避免触发Graph API的调用频率限制。 - 权限要求:确保调用API的身份拥有
User.Read.All和Directory.Read.All权限(应用权限或委派权限)。 - 性能优化:超大规模用户场景下,可使用Graph API的
$batch批量请求减少HTTP调用次数,提升处理效率。
内容的提问来源于stack exchange,提问作者thekevinkalis
相关产品推荐
相关产品推荐

