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

请求优化PowerShell脚本性能:查询MS Graph用户组归属信息

优化PowerShell脚本:批量查询用户组归属性能提升

原脚本执行慢的核心问题是:对每个授权用户单独调用Confirm-MgUserMemberGroup接口,每一次调用都要走网络请求,用户数量多的时候,累计的网络延迟和API开销会让执行时间急剧增加。

优化思路

反过来操作:先一次性获取目标4个组的所有成员ID,用哈希表存储成员关系,之后直接在本地判断用户是否属于各组,彻底避免循环内的API调用。

优化后的脚本

Import-Module Microsoft.Graph.Users, Microsoft.Graph.Groups

# 定义目标组:键是组ID,值是要显示的列名
$targetGroups = @{
    '123456789' = 'Group1'  # Group 1
    '987654321' = 'Group2'  # Group 2
    '154637485' = 'Group3'  # Group 3
    '856453756' = 'Group4'  # Group 4
}

Connect-MgGraph -Scopes 'User.Read.All', 'Group.Read.All'

# 获取目标SKU
$tmSku = Get-MgSubscribedSku -All | Where-Object SkuPartNumber -EQ 'SKU1'

# 获取持有SKU1的用户,保留需要的字段
$tmUsers = Get-MgUser -Filter "assignedLicenses/any(x:x/skuId eq $($tmSku.SkuId))" `
    -ConsistencyLevel eventual -CountVariable tmlicensedUserCount -All `
    | Select-Object DisplayName, Id, Mail, UserPrincipalName, JobTitle

Write-Host "Found $tmlicensedUserCount users."

# 预加载每个组的成员ID,存入哈希表(组ID -> 成员ID集合)
$groupMembers = @{}
foreach ($groupId in $targetGroups.Keys) {
    # 获取组的所有成员ID,用集合存储方便快速查询
    $members = Get-MgGroupMember -GroupId $groupId -All | Select-Object -ExpandProperty Id
    $groupMembers[$groupId] = [System.Collections.Generic.HashSet[string]]$members
}

# 为用户添加组归属标记
foreach ($user in $tmUsers) {
    # 初始化所有组列为No
    foreach ($colName in $targetGroups.Values) {
        $user | Add-Member -NotePropertyName $colName -NotePropertyValue 'No' -Force
    }

    # 检查用户是否在各组中,更新标记
    foreach ($groupId in $targetGroups.Keys) {
        $colName = $targetGroups[$groupId]
        if ($groupMembers[$groupId].Contains($user.Id)) {
            $user.$colName = 'Yes'
        }
    }
}

# 输出结果
$tmUsers

优化点说明

  1. 减少API请求次数:原脚本是N次请求(N为用户数),优化后仅4次请求(对应4个目标组),无论用户数量多少,API请求次数固定,大幅降低网络开销。
  2. 快速查询:用HashSet存储成员ID,判断用户是否属于组的操作是O(1)时间复杂度,比原脚本的数组-contains(O(n))更快。
  3. 代码扩展性更好:如果后续要增加/修改目标组,只需修改$targetGroups哈希表,无需改动后续判断逻辑。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 08:10:59