Azure中检查成员是否属指定组并导出至Excel的实现方案
Azure用户组归属检查并导出Excel的PowerShell解决方案
Azure没有原生工具直接生成你需要的这种用户-组归属对照表,用PowerShell可以轻松实现,下面是完整的解决方案:
准备工作
- 先安装Microsoft Graph PowerShell模块(替代即将退役的AzureAD模块,更推荐):
Install-Module Microsoft.Graph -Force -AllowClobber - 连接到Microsoft Graph,需要用户读取权限:
Connect-MgGraph -Scopes "User.Read.All", "GroupMember.Read.All"
完整脚本
# 1. 定义要检查的用户列表(可以是显示名称、邮箱或用户ID) $targetUsers = @( "User 1", "User 2", "User 3", "User 4" ) # 2. 定义要检查的组列表(显示名称或组ID) $targetGroups = @( "Group 1", "Group 2", "Group 3" ) # 3. 预获取所有目标组的ID(避免重复查询) $groupIds = @{} foreach ($groupName in $targetGroups) { $group = Get-MgGroup -Filter "displayName eq '$groupName'" if ($group) { $groupIds[$groupName] = $group.Id } else { Write-Warning "未找到组:$groupName" } } # 4. 构建结果数组 $results = @() foreach ($userName in $targetUsers) { # 获取用户对象 $user = Get-MgUser -Filter "displayName eq '$userName'" -Select DisplayName, Id if (-not $user) { Write-Warning "未找到用户:$userName" continue } # 创建结果对象,初始填充用户名 $resultObj = [PSCustomObject]@{ DisplayName = $user.DisplayName } # 检查用户在每个目标组中的归属 foreach ($groupName in $targetGroups) { $groupId = $groupIds[$groupName] if (-not $groupId) { continue } # 检查用户是否是组成员 $isMember = Get-MgGroupMember -GroupId $groupId -Filter "id eq '$($user.Id)'" -ErrorAction SilentlyContinue $resultObj | Add-Member -MemberType NoteProperty -Name $groupName -Value $(if ($isMember) { "Yes" } else { "No" }) } $results += $resultObj } # 5. 导出到Excel(需要安装ImportExcel模块,比原生Export-Csv更友好) # 安装ImportExcel模块:Install-Module ImportExcel -Force $results | Export-Excel -Path ".\用户组归属检查结果.xlsx" -AutoSize -BoldTopRow
输出示例
| DisplayName | Group 1 | Group 2 | Group 3 |
|---|---|---|---|
| User 1 | Yes | Yes | Yes |
| User 2 | Yes | No | Yes |
| User 3 | No | Yes | No |
| User 4 | Yes | Yes | Yes |
注意事项
- 如果用AzureAD模块,只需把
Get-Mg*替换成Get-AzureAD*对应命令,比如Get-AzureADUser、Get-AzureADGroup、Get-AzureADGroupMember - 若用户/组数量较多,建议批量查询提升效率,比如用
Get-MgUserByIds批量获取用户 ImportExcel模块需要单独安装,若不想用,也可以用Export-Csv导出为CSV文件,再用Excel打开:$results | Export-Csv -Path ".\用户组归属检查结果.csv" -Encoding UTF8 -NoTypeInformation
内容的提问来源于stack exchange,提问作者IT4Gov
相关产品推荐
相关产品推荐

