31 March 2015

Find domain controller with user replicated

When i'm creating a new user at the same time i'm trying to modify different properties on him like setup a manager, job title, include him in some groups ...and so on.

Sometimes the user is not replicated on all domain controllers in domain fast enough and any command after the New-ADUser will fail (with ADIdentityNotFoundException).

To overcome this problem i created a function that will find a domain controller on witch the user was replicated and used in the next commands as an argument for the Server parameter.


function Find-ReplicatedDC{
    param([string]$UserName)

    $AllDCinDomain = Get-ADDomainController -Filter *

    do{
        foreach( $DC in $AllDCinDomain){
                try{
                    $ADUser = Get-ADUser -Identity $username -Server $DC.HostName
                    $ReplicatedDC = $DC.HostName
                    break
                }
                catch{
                    Start-Sleep -Seconds 1
                }
        }
    }
    while(!$ReplicatedDC)

    return $ReplicatedDC
}

No comments:

Post a Comment