Script Repository


Add computers from an OU to user workstations

January 26, 2022
320

The script adds computers from a specific Organizational Unit to user workstations. Current computers in user workstations will remain unchanged. To execute the script, create a business rule, custom command or scheduled task configured for the User object type.

In the script, the $OUDN variable specifies the distinguished name (DN) of the Organizational Unit to search computers in.

Edit Remove
PowerShell
$OUDN = "OU=Computers,DC=domain,DC=com" #TODO: modify me

# Get current logon workstations
try
{
    $logonWorkstations = $Context.TargetObject.Get("userWorkstations")
}
catch
{
    $logonWorkstations = ""
}

# Search parameters
$searcher = $Context.BindToObjectByDN($OUDN)
$searcher.SearchFilter = "(&(objectCategory=computer)(dNSHostName=*))"
$searcher.SearchScope = "ADS_SCOPE_SUBTREE"
$searcher.PageSize = 500

try
{
    # Execute search
    $searchResultIterator = $searcher.ExecuteSearch()
    $searchResults = $searchResultIterator.FetchAll()
    
    if ($searchResults.Length -eq 0)
    {
        $Context.LogMessage("No computers were found.", "Information")
        return
    }
    
    foreach ($searchResult in $searchResults)
    {
        # Get computer DNS host name
        $computerDNSHostName = $searchResult.GetPropertyByName("dNSHostName").Values[0]        
        
        # Update workstations list
        if ($logonWorkstations -notlike "*$computerDNSHostName*")
        {
            $logonWorkstations = $logonWorkstations + "," + $computerDNSHostName
        }             
    }
    
    # Update the user
    $Context.TargetObject.Put("userWorkstations", $logonWorkstations)
    $Context.TargetObject.SetInfo()
}
finally
{
    # Release resources
    if ($searchResultIterator){ $searchResultIterator.Dispose() }
}

Comments ( 0 )
No results found.
Leave a comment