PowerShell实现AD空组查询、本地组清空及30天未使用本地组查询方法
PowerShell 组管理操作实现方案
1. 清空本地组所有成员
Win10/Server 2016及以上系统可直接使用内置的LocalAccounts模块实现,无需额外安装第三方工具:
# 导入本地账户管理模块 Import-Module Microsoft.PowerShell.LocalAccounts # 替换为你要操作的本地组名称 $targetGroup = "你的目标组名" # 获取组内所有成员并批量移除 Get-LocalGroupMember -Group $targetGroup | ForEach-Object { Remove-LocalGroupMember -Group $targetGroup -Member $_ }
执行命令需要管理员权限,操作内置特权组(如Administrators)前请确认不会误删必要管理员账户导致权限丢失
2. 查询超过30天未被使用的本地组
本地组无原生“最后使用时间”属性,以下方案基于「组最后修改时间+组成员最后登录时间」的组合判定逻辑,适配绝大多数业务场景:
Import-Module Microsoft.PowerShell.LocalAccounts $unusedThreshold = (Get-Date).AddDays(-30) $unusedLocalGroups = @() Get-LocalGroup | ForEach-Object { $currentGroup = $_ # 读取组最后修改时间 $groupLastModify = $currentGroup.LastWriteTime # 读取组内成员最近一次登录时间 $memberLastLogin = Get-LocalGroupMember -Group $currentGroup.Name -ErrorAction SilentlyContinue | ForEach-Object { if ($_.PrincipalSource -eq "Local") { try { (Get-LocalUser -Name $_.Name.Split('\')[-1]).LastLogin } catch { $null } } } | Where-Object { $_ -ne $null } | Sort-Object -Descending | Select-Object -First 1 # 符合未使用条件则加入结果集 if ($groupLastModify -lt $unusedThreshold -and (-not $memberLastLogin -or $memberLastLogin -lt $unusedThreshold)) { $unusedLocalGroups += [PSCustomObject]@{ 组名称 = $currentGroup.Name 组描述 = $currentGroup.Description 组最后修改时间 = $groupLastModify 成员最近登录时间 = $memberLastLogin ?? "无成员/无登录记录" } } } # 输出结果 $unusedLocalGroups | Format-Table -AutoSize
如果你的环境开启了对象访问审计,可将组相关的审计日志查询加入判定条件,结果会更精准
3. 查询AD空组
操作前需确保已安装RSAT的Active Directory模块,域控制器默认已预装该模块:
# 导入AD管理模块 Import-Module ActiveDirectory # 查询全域所有无成员的AD组,可通过SearchBase参数限定搜索的OU范围 Get-ADGroup -Filter * -Properties Members, Description | Where-Object { $_.Members.Count -eq 0 } | Select-Object Name, SamAccountName, Description, DistinguishedName | Format-Table -AutoSize
如需过滤系统内置的AD默认组,可在Where-Object条件中追加-and $_.GroupCategory -eq "Security"等过滤规则
内容的提问来源于stack exchange,提问作者Einstein
相关产品推荐
相关产品推荐

