powershelladgroup

powershell delete aduser groupmemberchip of other childdomain


script should delete a ADUser of all of his Groupmemberchips (including memberships in forestdomain and other childdomains), deactivate it and move it into another OU.

environment:

forest-domain: forest.com
child-domains: child1.forest.com
               child2.forest.com
               child3.forest.com

script is running in child1.forest.com

this is the script so far:

$username="testuser"
$groups=Get-ADPrincipalGroupMembership -Identity $username | where {$_.name -notlike "Domain Users"}

$getuser=Get-ADUser -Identity $username | select DistinguishedName
$userpath=$getuser.DistinguishedName

foreach ($group in $groups) {
   Remove-ADGroupMember -Identity $group -member $username -Confirm:$false
}

Disable-ADAccount -Identity $username
Move-ADObject "$userpath" -TargetPath "OU=Deaktivierte Benutzer,DC=child1,DC=forest,DC=com"

actually it successfull deletes all group-memberchips of child1.forest.com but not of forest.com or child2.forest.com

This code is working properly:

$User=Get-ADUser "testuser" -server "child1.forest.com"
$Group=Get-ADGroup "SomeGroup" -server "forest.com"
Remove-ADGroupMember $Group -Members $user -server "forest.com" -Confirm:$false

I tried to combine these script-snippets but not yet successful. I have an idea... to read the domain of the OU and pass it into the loop, but I dont get it working to read the OU in a way that I can use it.

Can someone help please?


Solution

  • found a solution, I query if the group exist in server:

    $found=0
    $servers=@("forest.com","child1.forest.com","child2.forest.com","child3.forest.com")
    $username="testuser"
    $user=Get-ADUser -Identity $username
    $groups=Get-ADPrincipalGroupMembership -Identity $user | where {$_.name -notlike "Domain Users"}
    
    foreach ($group in $groups) {
    
        foreach ($server in $servers) {        
            $groupname=$group.name
            $groupserver=Get-ADGroup $groupname -server $server
    
            if($groupserver)
            {
                $group=Get-ADGroup $groupname -server $server
                Remove-ADGroupMember $Group -Members $user -Confirm:$false -ErrorAction SilentlyContinue
                $found=1
            }
            if ($found -eq 1){break}
        }
    
    }