Script repository

Remove target user group ownership

Updated on: Jan 18, 2026, Views: 952

Miscellaneous

The script removes the target user from the list of owners of all groups. To execute the script, create a business rule, custom command or scheduled task configured for the User object type.

# Build criteria
$criteria = New-AdmCriteria "group" {directOwners -eq "%distinguishedName%"}

# Search parameters
$searcher = $Context.TargetObject
$searcher.Criteria = $criteria
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.PageSize = 500
$searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
$searcher.VirtualRoot = $True

try
{
    # Execute search
    $searchResultIterator = $searcher.ExecuteSearch()
    $searchResults = $searchResultIterator.FetchAll()
    
    if ($searchResults.Length -eq 0)
    {
        $Context.LogMessage("User %fullname% does not own any groups.", "Warning")
        return
    }
    
    foreach ($searchResult in $searchResults)
    {
        $group = $Context.BindToObjectBySearchResult($searchResult)
        
        # Check whether the group is on-premises one.
        if ($group.DirectoryType -eq 1)
        {
           # Remove the user from Managed By.
           $group.PutEx("ADS_PROPERTY_DELETE", "managedBy", @("%distinguishedName%"))
        }
        
        # Remove the user from group owners.
        $group.PutEx("ADS_PROPERTY_DELETE", "adm-ManagedByList", @("%distinguishedName%"))
        
        try
        {
            # Save the changes
            $group.SetInfo()
        }
        catch
        {
            $groupName = $group.Get("cn")
            $Context.LogMessage("Failed to remove %username% account from the $groupName group owners. " + $_.Exception.Message, "Warning")
        }
    }
}
finally
{
    # Release resources
    if ($searchResultIterator){ $searchResultIterator.Dispose() }
}

Comments 0

You must be signed in to comment.

    Got questions?

    Support Questions & Answers

    We use cookies to improve your experience.
    By your continued use of this site you accept such use.
    For more details please see our privacy policy and cookies policy.