1. 程式人生 > >通過powershell查詢OU中被禁用的AD賬號,並刪除他們的所屬組

通過powershell查詢OU中被禁用的AD賬號,並刪除他們的所屬組

port enable memberof sele lse mov rop acc identity

這個需求可以通過兩個方向來實現
1、找到禁用的賬號,刪除除domain users外的所有組,腳本內容如下

#導入AD模塊
import-module ActiveDirectory

#被禁用戶
$users = get-aduser -Filter * -SearchBase "OU=xxx,DC=xxx,DC=com" | foreach {if ($.enabled -eq $false){echo $.Name} }

#刪除用戶所有組
foreach($user in $users){
$Membership = Get-ADPrincipalGroupMembership $User

$group = $Membership.distinguishedName -ne "CN=Domain Users,CN=Users,DC=xxx,DC=com"
Remove-ADPrincipalGroupMembership -identity $User -MemberOf $group -confirm:$False
}

2、找到禁用賬號的samaccountname跟組,將domain users外的組通過samaccountname刪除成員,內容如下

import-module ActiveDirectory

$users = get-aduser -filter ‘enabled -eq $false‘ -Properties samaccountname, memberof -SearchBase "OU=xxx,DC=xxx,dc=com" | select samaccountname,

@{ n = ‘MemberOf‘; e = { ($.memberof | % { (Get-ADObject $).Name }) -join "," } }

Foreach ($user in $users)
{
Get-ADGroup -Filter { name -notlike "domain users" } | Remove-ADGroupMember -Members $user.samaccountname -Confirm:$False
}

通過powershell查詢OU中被禁用的AD賬號,並刪除他們的所屬組