Synchronizing Disabled User Accounts Between Active Directory Domains (forest) Using PowerShell

Managing multiple domains within an organization can be a complex task even more during migration phases which can last some times... One common challenge is ensuring that the user accounts are synchronized across domains, especially when disabling or deleting users in the source domain...

· 3 min read
Synchronizing Disabled User Accounts Between Active Directory Domains (forest) Using PowerShell

Managing multiple domains within an organisation can be a complex task even more during migration phases which can last some times... One common challenge is ensuring that the user accounts are synchronized across domains, especially when disabling or deleting users in the source domain. This script automates the process of disabling disabled user accounts in a source Active Directory (AD) domain and syncing them to a target AD domain using PowerShell.

Script Overview:

The script first imports the Active Directory module if not already imported. It then defines several variables, including the source domain name, target domain name, target domain controller FQDN, and OU path in the source domain. Additionally, the script creates a log file to record any errors or information during the execution of commands.

The script ensures that the log file directory exists before proceeding with the synchronization process. It then retrieves all disabled user accounts from the source OU using the Get-ADUser cmdlet and stores them in an array called $disabledUsersInSource. Any errors encountered during this process are logged in the specified log file.

Next, the script creates a new PowerShell session to the target domain controller using the Administrator account credentials. This enables the script to execute commands remotely on the target domain controller. Any errors encountered while creating the PSSession or running commands are also logged in the log file.

The script then defines a script block containing a parameterised function that will be executed in the target domain session. This script block retrieves all user accounts from the target domain and filters out any users that need to be disabled based on their SamAccountName existing in the $disabledUsersInSource array. For each of these users, the script attempts to disable them using the Set-ADUser cmdlet and logs the results in the log file.

Finally, the script removes the PSSession that was created for executing commands in the target domain session.

# Import Active Directory module if not already imported
if (-not (Get-Module -Name ActiveDirectory)) {
    Import-Module ActiveDirectory
}

$sourceDomain = "sourcedomain.local" # Replace with your source domain name
$targetDomain = "destinationdomain.local" # Replace with your target domain name
$targetDC = "dc.destinationdomain.local" # Replace with your target domain controller FQDN
$ouPath = "OU=Users,DC=sourcedomain,DC=local" # Replace with the OU path in the source domain
$logFile = "C:\logs\domain_sync.log" # Replace with the desired log file location

# Ensure the log file directory exists
$logFileDirectory = Split-Path -Path $logFile -Parent
if (-not (Test-Path -Path $logFileDirectory)) {
    New-Item -ItemType Directory -Path $logFileDirectory
}

# Get all disabled user accounts in the source OU
$disabledUsersInSource = @()
try {
    $disabledUsersInSource = Get-ADUser -Filter 'Enabled -eq $false' -SearchBase $ouPath -Server $sourceDomain -Properties SamAccountName | Select-Object SamAccountName
} catch {
    Write-Host "Error getting disabled users from source domain: $_"
    Write-Output "Error getting disabled users from source domain: $_" | Tee-Object -FilePath $logFile -Append
}

# Create a new PSSession to the target domain using the Administrator account
$cred = Get-Credential -Message "Enter credentials for target domain ($targetDomain)"
$targetSession = New-PSSession -ComputerName $targetDC -Credential $cred
try {
    # Script block to execute in the target domain session
    $scriptBlock = {
        param ($disabledUsersInSource, $logFile)

        # Get all user accounts in the target domain
        $allUsersInTarget = Get-ADUser -Filter * -Properties SamAccountName, Enabled | Select-Object SamAccountName, Enabled

        # Filter for users that need to be disabled in the target domain
        $usersToDisable = $allUsersInTarget | Where-Object {
            $_.Enabled -eq $true -and $disabledUsersInSource -contains $_.SamAccountName
        }

        foreach ($user in $usersToDisable) {
            try {
                Set-ADUser -Identity $user.SamAccountName -Enabled $false -ErrorAction Stop
                Write-Output "Disabling user $($user.SamAccountName)" | Out-File -FilePath $logFile -Append
            } catch {
                Write-Output "Failed to disable user $($user.SamAccountName): $_" | Out-File -FilePath $logFile -Append
            }
        }

        if ($usersToDisable.Count -eq 0) {
            Write-Output "No matching disabled users found to disable in the target domain." | Out-File -FilePath $logFile -Append
        } else {
            Write-Output "Processed $($usersToDisable.Count) users for disabling." | Out-File -FilePath $logFile -Append
        }
    }

    # Invoke the script block in the target domain session
    Invoke-Command -Session $targetSession -ScriptBlock $scriptBlock -ArgumentList $disabledUsersInSource.SamAccountName, $logFile

} catch {
    Write-Host "Error creating PSSession or running commands: $_"
    Write-Output "Error creating PSSession or running commands: $_" | Tee-Object -FilePath $logFile -Append
} finally {
    Remove-PSSession -Session $targetSession
}

To use this script, replace the placeholder values with your specific domain names, domain controller FQDN, OU path in the source domain, and log file location. Run the script to disable all disabled user accounts in the source domain that exist in the target domain and are enabled. The results of the synchronization process will be logged in the specified log file for further reference.

This PowerShell script provides a simple yet effective solution for synchronizing disabled user accounts between Active Directory domains, ensuring that administrators can easily maintain control over user access across multiple domains within their organization.