christoph.mue christoph.mue - 1 year ago 200
PowerShell Question

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.



script is running in

this is the script so far:

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

$getuser=Get-ADUser -Identity $username | select 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 but not of or

This code is working properly:

$User=Get-ADUser "testuser" -server ""
$Group=Get-ADGroup "SomeGroup" -server ""
Remove-ADGroupMember $Group -Members $user -server "" -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?

Answer Source

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

$user=Get-ADUser -Identity $username
$groups=Get-ADPrincipalGroupMembership -Identity $user | where {$ -notlike "Domain Users"}

foreach ($group in $groups) {

    foreach ($server in $servers) {        
        $groupserver=Get-ADGroup $groupname -server $server

            $group=Get-ADGroup $groupname -server $server
            Remove-ADGroupMember $Group -Members $user -Confirm:$false -ErrorAction SilentlyContinue
        if ($found -eq 1){break}

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download