The script adds a user to all the groups located in the same container as the user. In the script, the $searchScope variable specifies whether a user should be added to all groups located in the same container as the user (set to ADS_SCOPE_SUBTREE) or only to the groups directly located in the container (set to ADS_SCOPE_ONELEVEL). To execute the script, create a custom command, busienss rule or scheduled task configured for the User object type.
PowerShell
$searchScope = "ADS_SCOPE_SUBTREE" # TODO: modify me. Posible values: ADS_SCOPE_SUBTREE, ADS_SCOPE_ONELEVEL
# Get GUIDs of groups that user is currently member of
try
{
$groupGuidsBytes = $Context.TargetObject.GetEx("adm-DirectMemberOfGuid")
}
catch
{
$groupGuidsBytes = @()
}
# Build filter for searching groups
$filter = New-Object "System.Text.StringBuilder"
if ($groupGuidsBytes.Length -ne 0)
{
[void]$filter.Append("(&(objectCategory=group)")
foreach ($guidBytes in $groupGuidsBytes)
{
$guidFilter = [Softerra.Adaxes.Ldap.FilterBuilder]::Create("ObjectGuid", [Guid]$guidBytes)
[void]$filter.Append([Softerra.Adaxes.Ldap.FilterBuilder]::CreateNegation($guidFilter))
}
[void]$filter.Append(")")
}
else
{
[void]$filter.Append("(objectCategory=group)")
}
# Search groups
$searcher = $Context.BindToObject($Context.TargetObject.Parent)
$searcher.SearchFilter = $filter.ToString()
$searcher.SearchScope = $searchScope
$searcher.PageSize = 500
$searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
$searcher.SetPropertiesToLoad(@("name"))
try
{
$searchResultIterator = $searcher.ExecuteSearch()
$searchResults = $searchResultIterator.FetchAll()
# Add user to groups
foreach ($groupID in $searchResults)
{
$group = $Context.BindToObjectEx($groupID.AdsPath, $True)
try
{
$group.Add($Context.TargetObject.AdsPath)
}
catch
{
$groupName = $groupID.Properties["name"].Value
$Context.LogMessage("An error occurred while adding a user to group '$groupName': " + $_.Exception.Message, "Warning")
}
}
}
finally
{
# Release resources
$searchResultIterator.Dispose()
}