Andrew Ryan Davis
Andrew Ryan Davis

Reputation: 659

Remove group membership in AD Powershell script

I need to remove the groups in the "member of" section of users in a dead accounts OU.

The script runs and receives no errors, but the items in the list have not changed at all.

#Choose Organizational Unit
$SearchBase = "OU=Dead Accounts,DC=domain,DC=domain,DC=COM"
#Choose filtering parameters
$disabledaccounts = $SearchBase.children  
#Search through each item and perform x
foreach ($userObject in $disabledaccounts){  
        foreach ($group in $userObject.memberof)  
            {  
                $group = [ADSI]"LDAP://$group"  
                $group.remove("LDAP://$($userobject.distinguishedName)")   
            }} 

Doesn't seem to be working in my environment, though.

What is an easier way to write this, and can someone explain the bottom part? (group = [ADSI]"LDAP://$group" etc..)

Upvotes: 0

Views: 12818

Answers (1)

TheMadTechnician
TheMadTechnician

Reputation: 36297

Let's use the AD cmdlets for this, shall we? First we define where it's going to look, which you actually did you just never applied it anywhere...

#Choose Organizational Unit
$SearchBase = "OU=Dead Accounts,DC=domain,DC=domain,DC=COM"

Then we get a list of users that are located there (make sure to include the MemberOf property!):

$Users = Get-ADUser -filter * -SearchBase $SearchBase -Properties MemberOf

Now let's loop through those users, and for each group in their MemberOf property we'll remove the user from that group (the -Confirm:$false switch stops it from prompting you for every single removal... kind of vital for a script like this):

ForEach($User in $Users){
    $User.MemberOf | Remove-ADGroupMember -Member $User -Confirm:$false
}

We put it all together and we get:

#Choose Organizational Unit
$SearchBase = "OU=Dead Accounts,DC=domain,DC=domain,DC=COM"
$Users = Get-ADUser -filter * -SearchBase $SearchBase -Properties MemberOf
ForEach($User in $Users){
    $User.MemberOf | Remove-ADGroupMember -Member $User -Confirm:$false
}

Upvotes: 3

Related Questions