PowerShell Graph脚本提速优化:Azure AD 255用户查询耗时2分钟
Azure AD用户详情查询脚本性能优化思路
你的脚本性能瓶颈主要集中在每个用户重复调用Graph API获取MFA认证方法,255个用户会产生510次额外的API请求,加上多次嵌套的对象处理,导致整体耗时过长。以下是针对性的优化方案:
核心优化:批量获取MFA认证方法,避免逐用户API调用
原脚本在Select-Object的计算属性中,每个用户分别调用了两次Get-MgUserAuthenticationMicrosoftAuthenticatorMethod,这是最大的性能损耗点。改为先批量获取所有用户的MFA方法,再通过哈希表关联数据,将API请求次数从510次降低到1次。
其他优化点
- 合并嵌套的
Select-Object:减少不必要的对象转换开销 - 指定
-Select参数精简返回字段:只请求需要的属性,降低网络传输和解析成本 - 优先使用v1.0 API(若业务允许):beta版本API性能稳定性和响应速度通常不如正式版
优化后的脚本示例
Import-Module Microsoft.Graph.Users Import-Module Microsoft.Graph.Identity.SignIns Import-Module Microsoft.Graph.Authentication # 优先使用v1.0版本(若不需要beta独有属性) Select-MgProfile v1.0 Connect-MgGraph -Scopes User.Read.All, Organization.Read.All, AuditLog.Read.All, UserAuthenticationMethod.Read.All # 1. 批量获取目标用户列表,仅请求需要的字段 $users = Get-MgUser -CountVariable userCount -ConsistencyLevel eventual -All -Filter "UserType ne 'Guest'" ` -Select Id, CreatedDateTime, DisplayName, UserPrincipalName, LastPasswordChangeDateTime, OnPremisesDistinguishedName, SignInActivity # 2. 批量获取所有用户的Microsoft Authenticator认证方法,一次性API请求 $allMfaMethods = Get-MgUserAuthenticationMethod -All -Filter "methodType eq 'microsoftAuthenticator'" # 3. 构建哈希表,快速通过用户ID查找对应的MFA数据 $mfaLookup = @{} foreach ($method in $allMfaMethods) { $userId = $method.UserId if (-not $mfaLookup.ContainsKey($userId)) { $mfaLookup[$userId] = @{ DeviceTags = @() ClientApps = @() } } # 提取设备标签 if ($method.DeviceTag) { $mfaLookup[$userId].DeviceTags += $method.DeviceTag } # 提取客户端应用名(从AdditionalProperties中) if ($method.AdditionalProperties.clientAppName) { $mfaLookup[$userId].ClientApps += $method.AdditionalProperties.clientAppName } } # 4. 生成最终输出,直接从哈希表获取数据,无需再调用API $Output = $users | Select-Object ` Id, UserPrincipalName, DisplayName, CreatedDateTime, @{Name='LastSignInDateTime'; Expression={ $_.SignInActivity.LastSignInDateTime }}, LastPasswordChangeDateTime, @{Name='AuthMethod'; Expression={ if ($mfaLookup.ContainsKey($_.Id)) { $mfaLookup[$_.Id].DeviceTags -join ',' } else { '' } }}, @{Name='AuthClientApp'; Expression={ if ($mfaLookup.ContainsKey($_.Id)) { $mfaLookup[$_.Id].ClientApps -join ',' } else { '' } }}, OnPremisesDistinguishedName $Output
内容的提问来源于stack exchange,提问作者Rugbyball
相关产品推荐
相关产品推荐

