Hello Helmut,
It cannot be done by only updating the search filter. It is required to change the search base. Below is the version of the script that will perform the search only in the domain of the target group.
$propertyForUsernames = "adm-CustomAttributeText1" #TODO: modify me
function SearchObjects($filter)
{
$searcher = $Context.BindToObjectByDN("%adm-DomainDN%")
$searcher.SearchFilter = $filter
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.SizeLimit = 2
try
{
# Execute search
$searchResultIterator = $searcher.ExecuteSearch()
$searchResults = $searchResultIterator.FetchAll()
return ,$searchResults
}
finally
{
# Release resources
if ($searchResultIterator){ $searchResultIterator.Dispose() }
}
}
# Get usernames from the custom attribute
try
{
$sAMAccountNames = ($Context.TargetObject.Get($propertyForUsernames)).Split(",")
}
catch
{
return
}
# Get the current group members
try
{
$memberGuidsBytes = $Context.TargetObject.GetEx("adm-DirectMembersGuid")
}
catch
{
$memberGuidsBytes = @()
}
$memberGuids = New-Object "System.Collections.Generic.HashSet[System.Guid]"
$memberGuidsBytes | %%{ $memberGuids.Add([Guid]$_) }
$domainName = $Context.GetObjectDomain("%distinguishedName%")
foreach ($sAMAccountName in $sAMAccountNames)
{
$searchResults = SearchObjects "(sAMAccountName=$sAMAccountName)"
if ($searchResults.Length -eq 0)
{
$Context.LogMessage("Account with username $sAMAccountName not found.", "Warning")
continue
}
elseif ($searchResults.Length -gt 1)
{
$Context.LogMessage("Found more than one account with username $sAMAccountName", "Warning")
continue
}
# Add the user to the group
$userGuid = [Guid]$searchResults[0].Properties["objectGUID"].Value
if (-not($memberGuids.Contains($userGuid)))
{
try
{
$Context.TargetObject.Add("Adaxes://<GUID=$userGuid>")
}
catch
{
$Context.LogMessage("An error occurred when addingaccount with username $sAMAccountName to the group. Error: " + $_.Exception.Message, "Warning") # TODO: modify me
}
}
else
{
$Context.LogMessage("User $sAMAccountName is already a member of the group.", "Information") # TODO: modify me
}
}
# Clear custom attribute
$Context.TargetObject.Put($propertyForUsernames, $NULL)
$Context.TargetObject.SetInfoEx(@($propertyForUsernames))