Script repository
The script adds the target user to the group named after the specified template based on a property value. If a group with the name does not exist, it will be created. To execute the script, create a business rule, custom command or scheduled task configured for the User object type.
Parameters
$groupName- the group name template. In the template, the{0}placeholder will be replaced with the value of the property specified in the$propertyNamevariable.$groupOuDn- the distinguished name (DN) of the Organizational Unit where to create a group if it does not exist. For information on how to get an object DN, see Get the DN of a directory object.$groupType- the type of group to create if it does not exist$propertyName- the name of the property used to form the group name.
$groupName = "Group-{0}" # TODO: modify me
$groupOuDn = "OU=Groups,OU=DraculaTest,OU=Adaxes Test OU,DC=adaxeslab,DC=local" # TODO: modify me
[Softerra.Adaxes.Interop.Adsi.ADS_GROUP_TYPE_ENUM]$groupType =
"ADS_GROUP_TYPE_GLOBAL_GROUP, ADS_GROUP_TYPE_SECURITY_ENABLED" # TODO: modify me
$propertyName = "department" # TODO: modify me
# Get property value
try
{
$propertyValue = $Context.TargetObject.Get($propertyName)
}
catch
{
$Context.LogMessage("Property $propertyName is not specified.", "Information")
return
}
$groupName = [System.String]::Format($groupName, $propertyValue)
# Get GUIDs of groups user is a direct member of
try
{
$groupGuidsBytes = $Context.TargetObject.GetEx("adm-DirectMemberOfGuid")
}
catch
{
$groupGuidsBytes = @()
}
$groupGuids = New-Object "System.Collections.Generic.HashSet[System.Guid]"
$groupGuidsBytes | %%{[void]$groupGuids.Add([Guid]$_)}
# Search for group
$searcher = $Context.TargetObject
$searcher.Criteria = New-AdmCriteria "group" -Expression {name -eq $groupName}
$searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
$searcher.SetPropertiesToLoad(@("ObjectGuid"))
$searcher.VirtualRoot = $True
try
{
# Execute search
$searchResultIterator = $searcher.ExecuteSearch()
$searchResults = $searchResultIterator.FetchAll()
if ($searchResults.Length -eq 0)
{
# Create group
$targetContainer = $Context.BindToObjectByDN($groupOuDn)
$group = $targetContainer.Create("group","CN=$groupName")
$group.Put("groupType", [Int32]$groupType)
$group.Put("sAMAccountName", $groupName)
$group.SetInfo()
# Add user to group
$group.Add($Context.TargetObject.AdsPath)
return
}
foreach ($searchResult in $searchResults)
{
$guid = [Guid]$searchResult.Properties["ObjectGuid"].Value
if ($groupGuids.Contains($guid))
{
continue
}
# Add user to group
$group = $Context.BindToObject($searchResult.AdsPath)
$group.Add($Context.TargetObject.AdsPath)
}
}
catch
{
$Context.LogMessage("An error occurred when adding the user to group '$groupName'. Error: " + $_.Exception.Message, "Warning")
}
finally
{
# Release resources
if ($searchResultIterator){ $searchResultIterator.Dispose() }
}
Comments 0
You must be signed in to comment.