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

Set manager based on property value

October 04, 2022 Views: 644

The script finds a user according to the property values mapping and sets the user as the manager of the target account. To execute the script, create a scheduled task, business rule or custom command configured for the User object type.

Parameters:

  • $propertyName - Specifies the LDAP name of the property whose values will be used to find manager for the target account.
  • $valueMap - Maps target user proeprty values with the values of the managers.
  • $pipelined - Specifies whether to pass the update through the Adaxes pipeline (e.g. to trigger business rules).
Edit Remove
PowerShell
$propertyName = "title" # TODO: modify me
$valueMap = @{
    "IT" = "Director of IT"
    "Support" = "Director of Support"
} # TODO: modify me
$pipelined = $True # TODO: modify me

# Get user property value
try
{
    $propertyValue = $Context.TargetObject.Get($propertyName)
}
catch
{
    $Context.LogMessage("Property $propertyName is not specified for user %fullname%.", "Warning")
    return
}

# Get manager property value
foreach ($item in $valueMap.GetEnumerator())
{
    if ($item.Name -ne $propertyValue)
    {
        continue
    }
    
    $managerValue = $item.Value
    break    
}

if ([System.String]::IsNullOrEmpty($managerValue))
{
    $Context.LogMessage("No manager value is specified for value $propertyValue.", "Warning")
    return
}

# Search parameters
$searcher = $Context.TargetObject
$searcher.SearchFilter = "(&(sAMAccountType=805306368)($propertyName=$managerValue))"
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.SizeLimit = 2
$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("Could not find user with $propertyName equal $managerValue.", "Warning")
        return
    }
    elseif ($searchResults.Length -eq 2)
    {
        $Context.LogMessage("Found more than one user with $propertyName equal $managerValue.", "Warning")
        return
    }
    
    # Get manager DN
    $managerDN = $searchResults[0].GetPropertyByName("distinguishedName").Values[0]
    
    # Update target user
    $user = $Context.BindToObjectByDNEx("%distinguishedName%", $pipelined)
    $user.Put("manager", $managerDN)
    $user.SetInfo()
}
finally
{
    # Release resources
    if ($searchResultIterator){ $searchResultIterator.Dispose() }
}
Comments 0
Leave a comment
Loading...

Got questions?

Support Questions & Answers