Script Repository


Remove users located in specific OUs from the unmanaged list

November 02, 2021
140

The script removes users located in specific OUs from the unmanaged list. To execute the script, create a scheduled task configured for the Domain-DNS object type and assign it over any of your AD domains.

In the script, the $ouDNs variable specifies distinguished names (DNs) of the Organizational Units users located in which will be removed from unmanaged accounts. For information on how to get an object DN, see https://adaxes.com/sdk/HowDoI.GetDnOfObject/.

Edit Remove
PowerShell
$ouDNs = @(
    "OU=Users,OU=Department1,DC=domain,DC=com",
    "OU=Users,OU=Department2,DC=domain,DC=com"
) # TODO: modify me

# Bind to the 'Configuration Set Settings' container
$configurationSetSettingsPath = $Context.GetWellKnownContainerPath("ConfigurationSetSettings")
$configurationSetSettings = $Context.BindToObject($configurationSetSettingsPath)
     
# Get all unmanaged accounts
$allUnmanagedSids = New-Object "System.Collections.Generic.HashSet[String]"
$configurationSetSettings.GetUnmanagedAccounts(@()) | %%{[void]$allUnmanagedSids.Add($_.Key)}

foreach ($dn in $ouDNs)
{
    # Find users and get their SIDs
    $searcher = $Context.BindToObjectByDN($dn)
    $searcher.SearchFilter = "(sAMAccountType=805306368)"
    $searcher.SearchScope = "ADS_SCOPE_SUBTREE"
    $searcher.PageSize = 500
    
    try
    {
        $searchResultIterator = $searcher.ExecuteSearch()
        $searchResults = $searchResultIterator.FetchAll()
        
        foreach ($searchResult in $searchResults)
        {
            $sidBytes = $searchResult.Properties["objectSid"].Value
            $sid = New-Object "Softerra.Adaxes.Adsi.Sid" @($sidBytes, 0)
            [void]$allUnmanagedSids.Remove($sid.Value)
        }
    }
    finally
    {
        # Release resources
        if ($searchResultIterator){ $searchResultIterator.Dispose() }
    }
}

# Save changes
$configurationSetSettings.SetUnmanagedAccounts(@($allUnmanagedSids))

Comments ( 0 )
No results found.
Leave a comment