Find user across 4 domains

Hi guys, my company has 4 domains.
In order to search inside foreign domains, you need to specify a domain controller from that domain. Let’s call them dc1, dc2, dc3, dc4
I want to search for a specific user across all domains, but I don’t know how to do it. This is how my idea looks like:

Function FindUser {Get-ADUser “username” -Server $domaincontroller}

Try {
$domaincontroller = “dc1”
FindUser
}
Catch {
$domaincontroller = “dc2”
FindUser}
Catch {
$domaincontroller = “dc3”
FindUser}
Catch {
$domaincontroller = “dc4”
FindUser}

The problem is, I can only use Catch once :slight_smile:
Can you help me find the way how to search all 4 dc’s ?

My first thought was a do…until loop. Something like:

$i = 0
$DCs = "dc1", "dc2", "dc3", "dc4"
Do {
 Try {
  FindUser -server $DCs[$i] -ea stop
  $found = $true
 }
 Catch {
  $found = $false
 }
}
Until ($found -or $i -eq ($DCs.GetUpperBound(0)))

You would need to add a parameter to your FindUser function to take the server name as well but that seems to be the way to handle it.

It’s worth pointing out that you can use multiple catch statements but not in the way you used it. Catch on it’s own will act as a catch all, but you can have other catches for specific errors such as a user not being found, another for server not reachable etc. It wouldn’t help you for this as the error is always the same (user not found) but i thought it was worth pointing out.

Matt seems to be on the right track for this situation. You’ll just have to loop through a list of your domain controllers until you find the user. You could use just about any loop structure… Depending on how your trusts and accounts are set up, you may have to change the credentials used in each call, too.

$cred1 = Get-Credential -UserName “domain1\user1” -Message “domain1 user”
$cred2 = Get-Credential -UserName “domain2\user1” -Message “domain2 user”
$cred3 = Get-Credential -UserName “domain3\user1” -Message “domain3 user”
$cred4 = Get-Credential -UserName “domain4\user1” -Message “domain4 user”

$creds = $cred1, $cred2, $cred3, $cred4
$dcs = “dc1”, “dc2”, “dc3”, “dc4”

$user = $null
foreach ($i=0; $i -lt $dcs.Count; $i++) {
$user = Get-ADUser -Identity $username -Server $dcs[$i] -Credential $creds[$i]
if ($user) {
break
}
}

Code is not tested!