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.

Script Repository

Remove target user group ownership

November 01, 2023 Views: 151

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

Edit Remove
PowerShell
# 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
Leave a comment
Loading...

Got questions?

Support Questions & Answers