Script Repository


Add users located in particular Organizational Units to Unmanaged Accounts

March 22, 2019
1776

The script adds users located in particular Organizational Units to Unmanaged Accounts.

To keep the list of Unmanaged Accounts in line with changes in your AD, you need to create a Scheduled Task configured for the Domain-DNS object type that runs the script and assign it over any of your AD domains.

Specify Organizational Units directly in the script

In this version of the script, you can specify the Organizational Units with Unmanaged Accounts directly in the script.

Parameter:

  • $ouDNs - specifies the distinguished names (DNs) of the Organizational Units where you don't want to manage users;
  • $replaceCurrentlyUnmanagedAccounts - specifies whether to replace the accounts that are currently unmanaged or add the users located in the specified OUs to the existing list;
  • $excludeUserDNs - specifies the distinguished names (DNs) of the user accounts that should not be added to the unmanaged accounts list even if they are located in the specified OUs. If all child objects of the OUs should be added to the list, leave the array empty.
Edit Remove
PowerShell
$ouDNs = @(
    "OU=Unmanaged Accounts 1,DC=example,DC=com",
    "OU=Unmanaged Accounts 2,DC=example,DC=com") # TODO: modify me
$excludeUserDNs = @(
    "CN=My User 1,CN=Users,DC=domain,DC=com",
    "CN=My User 2,CN=Users,DC=domain,DC=com") # TODO: modify me

$replaceCurrentlyUnmanagedAccounts = $True # TODO: modify me

function GetUserSids($ouDNs, $filter, $allUnmanagedSids)
{
    foreach ($ouDN in $ouDNs)
    {
        # Find enabled and not expired users within the OU
        $searcher = $Context.BindToObjectByDN($ouDN)
        $searcher.PageSize = 500
        $searcher.SearchScope = "ADS_SCOPE_SUBTREE"
        $searcher.SearchFilter = $filter
        $searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
        $searcher.SetPropertiesToLoad(@("objectSid"))
        
        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.Add($sid.Value)
            }
        }
        finally
        {
            # Release resources
            $searchResultIterator.Dispose()
        }
    }
}

# Build filter
$filter = New-Object "System.Text.StringBuilder"
$currentDate = (Get-Date).ToFileTime()
[void]$filter.Append("(&(sAMAccountType=805306368)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(|(accountExpires>=$currentDate)(accountExpires=0)(accountExpires=9223372036854775807))")
foreach ($dn in $excludeUserDNs)
{
    $filterPart = [Softerra.Adaxes.Ldap.FilterBuilder]::Create("distinguishedName", $dn)
    [void]$filter.Append("(!$filterPart)")
}
[void]$filter.Append(")")

# Get SIDs of all users located in the OUs
$allUnmanagedSids = New-Object "System.Collections.Generic.HashSet[String]"
GetUserSids $ouDNs $filter.ToString() $allUnmanagedSids

# Add users to unmanaged accounts
$configurationSetSettingsPath = $Context.GetWellKnownContainerPath("ConfigurationSetSettings")
$configurationSetSettings = $Context.BindToObject($configurationSetSettingsPath)

if (!$replaceCurrentlyUnmanagedAccounts)
{
    # Fetch user accounts that are already unmanaged
    $currentUnmanagedAccounts = $configurationSetSettings.GetUnmanagedAccounts(@())
    $currentUnmanagedAccounts | %%{[void]$allUnmanagedSids.Add($_.Key)}
}

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

Import Organizational Units from CSV

This version of the script allows you to import a list of Organizational Units with Unmanaged Accounts from a CSV file. The OUs must be specified in the file by their Distinguished Name (DN).

Parameters:

  • $csvFilePath - specifies a path to the CSV file that contains a list of OUs with Unmanaged Accounts;
  • $ouDNColumnName - specifies the name of the CSV column that contains the OU DNs.
Edit Remove
PowerShell
$csvFilePath = "\\Server\Share\OrganizationalUnits.csv" # TODO: modify me
$ouDNColumnName = "DistinguishedName" # TODO: modify me

function GetUserSids($ouDNs)
{
    foreach ($ouDN in $ouDNs)
    {
        # Find enabled and not expired users within the OU
        $searcher = $Context.BindToObjectByDN($ouDN)
        $searcher.PageSize = 500
        $searcher.SearchScope = "ADS_SCOPE_SUBTREE"
        $currentDate = (Get-Date).ToFileTime()
        $searcher.SearchFilter = "(&(sAMAccountType=805306368)(!(userAccountControl:1.2.840.113556.1.4.803:=2))(|(accountExpires>=$currentDate)(accountExpires=0)(accountExpires=9223372036854775807)))"
        $searcher.ReferralChasing = "ADS_CHASE_REFERRALS_NEVER"
        $searcher.SetPropertiesToLoad(@("objectSid"))

        try
        {
            $searchResultIterator = $searcher.ExecuteSearch()
            $searchResults = $searchResultIterator.FetchAll()
            
            # Get the SID of each user
            foreach ($searchResult in $searchResults)
            {
                $sidBytes = $searchResult.Properties["objectSid"].Value
                $sid = New-Object "Softerra.Adaxes.Adsi.Sid" @($sidBytes, 0)
    
                [void]$userSids.Add($sid.ToString())
            }
        }
        finally
        {
            # Release resources
            if ($searchResultIterator){ $searchResultIterator.Dispose() }
        }
    }
}

# Import CSV
$records = Import-Csv -Path $csvFilePath -ErrorAction Stop

# Get OU DNs
$ouDNs = $records | %%{$_.$ouDNColumnName}
if ($ouDNs -eq $NULL)
{
    return
}

# Get user SIDs
$userSids = New-Object "System.Collections.Generic.HashSet[String]"
GetUserSids $ouDNs

# Update the list of Unmanaged Accounts
$configurationSetSettingsPath = $Context.GetWellKnownContainerPath("ConfigurationSetSettings")
$admConfigurationSetSettings = $Context.BindToObject($configurationSetSettingsPath)

$admConfigurationSetSettings.SetUnmanagedAccounts(@($userSids))

Comments ( 0 )
No results found.
Leave a comment