Find user

When creating an Email account in Exchange I often run into the issue Exchange does not know the User account exists in Active Directory right after creating it. My idea was to create a cmdlet extension in Exchange that looks for the user account through each domain controller and stops when it reaches a domain controller that knows about the account, then uses that domain controller to create the mailbox.

(BTW, I cannot use AD cmdlets)

I was trying to following, but I did not get expected results:

$domaincontrollers = Get-DomainController

foreach ($dc in $domaincontrollers)
{
$dcString = ($dc.name).tostring()
Get-User useraccount -DomainController $dcString -ErrorVariable errorInDC
if ($errorInDC -eq $null)
{
break
}
}
$dcString #this should have the first DC that found the account and we should stop searching at this DC…

You could probably just put a delay into your script. The problem is likely just the wait for AD replication to happen. Searching through all the DCs is definitely a lot of work.

You said you didn’t get the expected results. What results did you expect, and what did you get?

The problem is definitely waiting for AD replication to take place. In my environment there are only 3 sites with 2 domain controllers each so it doesnt take too long to look through them. What I expected my script to do is: view comments in bold

 

 

$domaincontrollers = Get-DomainController #gets all domain controllers

foreach ($dc in $domaincontrollers)Â #loop through each domain controller
{
$dcString = ($dc.name).tostring() #convert the DC name to a string
Get-User useraccount -DomainController $dcString -ErrorVariable errorInDCÂ #get the user account and if there is an error, store it in the errorInDC varaiable
if ($errorInDC -eq $null)Â #if there is no error in the get-user command, break out of the foreach loop
{
break
}
}
$dcString #this should have the first DC that found the account and we should stop searching at this DC…

What is actually happening is, it is checking all DC’s and using the last DC checked in the $dcString variable.

So that is probably your error capturing trick not working. I’d suggest leaving off -ErrorVariable, because it isn’t getting populated the way you think or want it to. Â Instead, maybe assign the results of Get-User to a variable, and then check to see if the variable is null or not.

Or, add -ErrorAction Stop to Get-User, and trap the error. Problem is, I don’t have the cmdlet in front of me to test - I don’t know that it actually throws an exception (as opposed to an error) when you tell it to get a user that doesn’t exist. You’ll have to play with that a little bit, but it’s why you’re getting the results you are.