Script Repository


Copy user properties and group membership

June 20, 2017
1883

The script can be used in Business Rules, Custom Commands and Scheduled Tasks to copy property values and group memberships from a user to another user. To copy properties from a user, specify that user in the target user account using a property specified by $source. Then, execute the script on the user account that will receive the copied properties and group memberships.

To add the script to a Business Rule, Custom Command or Scheduled Task, use the Run a program or PowerShell script action.

Parameters:

  • $source - specifies the property that will be used to specify the source user. Use a property that supports the DN syntax, for example, assistant.
  • $propertiesToCopy - specifies the properties of the source user that will be copied.
Edit Remove
PowerShell
$source = "assistant" # TODO: modify me
$propertiesToCopy = @("displayName", "physicalDeliveryOfficeName", "telephoneNumber", "mail", "employeeID", "employeeType") # TODO: modify me

# Bind to the source user
try
{
    $sourceUserDN = $Context.TargetObject.Get($source)
    $sourceUser = $Context.BindToObjectByDN($sourceUserDN)
}
catch
{
    $Context.LogMessage("The user to copy properties from is not specified", "Warning")
    return
}

# Update properties
foreach($propertyName in $propertiesToCopy)
{
    try
    {
        $propertyValue = $sourceUser.Get($propertyName)
    }
    catch
    {
        continue # The property is empty
    }
    
    $Context.TargetObject.Put($propertyName, $propertyValue)
}

# Save changes
$Context.TargetObject.SetInfo()

# Get group memberships
try
{
    $groupGuidsInBytes = $sourceUser.GetEx("adm-DirectMemberOfGuid")
}
catch
{
    $Context.LogMessage($sourceUser.Name + " is not a member of any groups", "Information")
    return
}

# Get the ID of the target user's primary group
$primaryGroupId = $Context.TargetObject.Get("primaryGroupID")

# Add target user to groups
$Context.LogMessage("Adding the user to groups:", "Information")
foreach ($groupGuidBytes in $groupGuidsInBytes)
{
    $groupGuid = New-Object "System.Guid" (,$groupGuidBytes)
    $groupGuid = $groupGuid.ToString("B")
    $group = $Context.BindToObject("Adaxes://<GUID=$groupGuid>")
    
    # Skip the group if it is the primary group for the user
    if ($group.Get("primaryGroupToken") -eq $primaryGroupId)
    {
        continue
    }
    
    try
    {
        $group.Add($Context.TargetObject.AdsPath)
    }
    catch
    {
        $Context.LogMessage($group.Get("name") + ": " + $_.Exception.Message, "Warning")
    }
}


Comments ( 0 )
No results found.
Leave a comment