Query the OU for disabled ad accounts through PowerShell and delete their owning group

Source: Internet
Author: User
Tags samaccountname

This requirement can be achieved in two directions.
1. Find the disabled account and delete all the groups except domain users, the script content is as follows

#导入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, find the disabled account sAMAccountName and group, the group outside the domain users through sAMAccountName delete members, the content is as follows

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
}

Query the OU for disabled ad accounts through PowerShell and delete their owning group

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.