请求编写PowerShell脚本移除指定Azure组中的禁用用户
针对单个Azure AD组移除禁用用户的PowerShell脚本
前置准备
- 安装 Microsoft Graph PowerShell模块(替代即将弃用的AzureAD模块),执行命令:
Install-Module Microsoft.Graph -Scope CurrentUser -Force - 确保你的CSV文件包含用户标识列(比如
UserPrincipalName或ObjectId),文件格式示例:UserPrincipalName disabled.user1@contoso.com disabled.user2@contoso.com
完整脚本
# 连接到Microsoft Graph,需要Group.ReadWrite.All和User.Read.All权限 Connect-MgGraph -Scopes "Group.ReadWrite.All", "User.Read.All" # 1. 定义目标Azure AD组的信息(二选一即可) $targetGroupId = "你的目标组ObjectId" # 或者使用组名查找(如果组名唯一) # $targetGroupId = (Get-MgGroup -Filter "DisplayName eq '目标组名称'").Id # 2. 导入禁用用户的CSV文件(替换为你的文件路径) $disabledUsers = Import-Csv -Path "C:\path\to\disabled-users.csv" # 3. 循环处理每个用户,从目标组移除 foreach ($user in $disabledUsers) { # 获取用户的ObjectId(如果CSV用的是UserPrincipalName) $userObjectId = (Get-MgUser -Filter "UserPrincipalName eq '$($user.UserPrincipalName)'").Id if ($userObjectId) { # 检查用户是否在目标组中 $isMember = Get-MgGroupMember -GroupId $targetGroupId -Filter "Id eq '$userObjectId'" -ErrorAction SilentlyContinue if ($isMember) { # 执行移除操作,先加-WhatIf参数测试(移除-WhatIf才会实际执行) Remove-MgGroupMemberByRef -GroupId $targetGroupId -DirectoryObjectId $userObjectId -WhatIf Write-Host "已标记移除用户 $($user.UserPrincipalName) 从目标组" -ForegroundColor Cyan } else { Write-Host "用户 $($user.UserPrincipalName) 不在目标组中,跳过" -ForegroundColor Yellow } } else { Write-Host "未找到用户 $($user.UserPrincipalName),跳过" -ForegroundColor Red } } # 断开Graph连接 Disconnect-MgGraph
关键说明
- 测试优先:脚本中默认带有
-WhatIf参数,执行时只会输出操作内容不会实际移除用户,确认无误后再移除该参数。 - 权限要求:执行脚本的账号需要拥有Azure AD组读写权限和用户读取权限。
- 用户标识:如果你的CSV用的是
ObjectId而非UserPrincipalName,可以直接使用$user.ObjectId替换脚本中的$user.UserPrincipalName相关逻辑。 - 避免误操作:脚本会先检查用户是否在目标组中,仅对组内的禁用用户执行移除,不会影响其他组或活跃用户。
内容的提问来源于stack exchange,提问作者littlegreywagon1
相关产品推荐
相关产品推荐

