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 users located in particular Organizational Units to unmanaged accounts

December 05, 2022 Views: 6063

The scripts add enabled and not expired users located in particular Organizational Units to unmanaged accounts. To execute either of the scripts, create a scheduled task configured for the Domain object type and assign it over any of your managed domains.

Specify Organizational Units directly in the script

In this version of the script, you can specify the Organizational Units users located in which will be added to unmanaged accounts directly in the script. The script only adds enabled and not expired users to the unmanged list.

Parameter:

  • $ouDNs - Specifies distinguished names (DNs) of the Organizational Units users located in which will be added to unmanaged accounts.
  • $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 distinguished names (DNs) of users 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, $criteria, $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.Criteria = $criteria
        $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 criteria
$criteria = New-AdmCriteria -Type "user" -Expression {accountDisabled -eq $False -and accountExpires -expired $False}
foreach ($dn in $excludeUserDNs)
{
    $criteria["user"].Add({distinguishedName -ne $dn})
}

# Get SIDs of all users located in the OUs
$allUnmanagedSids = New-Object "System.Collections.Generic.HashSet[String]"
GetUserSids $ouDNs $criteria $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 the list of Organizational Units users located in which will be added to unmanaged accounts from a CSV file. The file should contain distinguished names (DNs) of the OUs. The script only adds enabled and not expired users to the unmanged list.

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.Criteria = New-AdmCriteria -Type "user" -Expression {accountDisabled -eq $False -and accountExpires -expired $False}
        $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))

Script for external execution

This version of the script must be executed in Windows PowerShell on the computer where Adaxes service runs. To execute the script, log in to the computer with the credentials of the Adaxes service account.

Parameter:

  • $ouDNs - Specifies distinguished names (DNs) of the Organizational Units users located in which will be added to unmanaged accounts.
  • $replaceCurrentlyUnmanagedAccounts - Specifies whether to replace the accounts that are currently unmanaged or add the users located in the specified OUs to the existing list.
Edit Remove
PowerShell
[Reflection.Assembly]::LoadWithPartialName("Softerra.Adaxes.Adsi") 
Import-Module Adaxes

# Connect to the Adaxes service
$admNS = New-Object "Softerra.Adaxes.Adsi.AdmNamespace" 
$admService = $admNS.GetServiceDirectly("localhost")

$ouDNs = @(
    "OU=Unmanaged Accounts 1,DC=example,DC=com",
    "OU=Unmanaged Accounts 2,DC=example,DC=com") # TODO: modify me

$replaceCurrentlyUnmanagedAccounts = $True # TODO: modify me

function GetUserSids($ouDNs, $criteria, $allUnmanagedSids)
{
    foreach ($ouDN in $ouDNs)
    {
        # Find enabled and not expired users within the OU
        $searcher = $admService.OpenObject("Adaxes://$ouDN", $NULL, $NULL, 0)
        $searcher.PageSize = 500
        $searcher.SearchScope = "ADS_SCOPE_SUBTREE"
        $searcher.Criteria = $criteria
        $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 criteria
$criteria = New-AdmCriteria -Type "user" -Expression {accountDisabled -eq $False -and accountExpires -expired $False}

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

# Bind to the 'Configuration Set Settings' container
$configurationSetSettingsPath = $admService.Backend.GetConfigurationContainerPath("ConfigurationSetSettings")
$configurationSetSettings = $admService.OpenObject($configurationSetSettingsPath, $NULL, $NULL, 0)

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

# Save changes
$configurationSetSettings.SetUnmanagedAccounts(@($allUnmanagedSids))
Comments 0
Leave a comment
Loading...

Got questions?

Support Questions & Answers