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

Add computer account to a group based on username and department

February 18, 2021 Views: 2040

The script finds a computer whose username contains the username of the target user and adds to a group mathcing the user department. In the script, the $departmentInfos variable matches department names with names of the corresponding groups. To run the script, use a busienss rule, custom command or scheduled task configured for the User object type.

Edit Remove
$departmentInfos = @{
    "Sales" = "Comp_Sales"
    "IT" = "Comp_IT"
} # TODO: modify me. Example $departmentInfos = @{"<department name>" = "<group_name>"}

function GetObjectPath($filter, $domainName)
    $searcher = $Context.BindToObject("Adaxes://$domainName/rootDSE")
    $searcher.SearchFilter = $filter
    $searcher.SearchScope = "ADS_SCOPE_SUBTREE"
    $searcher.SizeLimit = 1
        $searchResultIterator = $searcher.ExecuteSearch()
        $searchResults = $searchResultIterator.FetchAll()
        if ($searchResults.Length -eq 0)
            return $NULL
        return $searchResults[0].AdsPath
        # Release resources
        if ($searchResultIterator){ $searchResultIterator.Dispose() }

# Get the computer path
$domainName = $Context.GetObjectDomain("%distinguishedName%")
$computerPath = GetObjectPath "(&(objectCategory=computer)(sAMAccountName=*%username%*))" $domainName
if ($computerPath -eq $NULL)
    $Context.LogMessage("A user's computer could not be found", "Warning")

# Search group matching the user department
$groupName = $departmentInfos["%department%"]
if ($groupName -eq $NULL)
    $Context.LogMessage("No group specifieded for department %department%.", "Warning")
$groupPath = GetObjectPath "(&(objectCategory=group)(sAMAccountName=$groupName))" $domainName
if ($groupPath -eq $NULL)
    $Context.LogMessage("Group $groupName does not exist.", "Warning")

# Add the computer to group
$group = $Context.BindToObject($groupPath)

Comments 0
Leave a comment

Got questions?

Support Questions & Answers