Karimi
Karimi

Reputation: 1477

How to validate an email exists in an Active Directory forest

I'm looking to write a PowerShell script which validates whether a list of emails within a file are valid against the Active Directory forest. I have a script which works for my specific domain, but it doesn't find emails associated to other domains within the corporate forest.

foreach($line in Get-Content C:\path\emails.txt) {
    if(Get-ADUser -Filter "EmailAddress -like '$line'") {
        "$line is valid"
    }
    else {
        "$line is invalid"
    }
}

Result:

[email protected] is valid
[email protected] is valid
[email protected] is invalid

[email protected] returns invalid because it's part of another domain, but I'd like it to return valid since it's part of the corporate forest.

Upvotes: 1

Views: 3635

Answers (3)

Karimi
Karimi

Reputation: 1477

The following solution worked. It takes elements of the proposed solutions and cycles through all the domain controllers. I would have preferred to leverage the Get-ADForest cmdlet in a way to prevent the need to specify DCs, but this suffices for the problem's purpose.

foreach($line in Get-Content C:\path\emails.txt) {
        foreach($DC in Get-Content C:\path\DCs.txt){
            if(Get-ADUser -Filter "EmailAddress -like '$line'" -Server $DC) {
                "$line FOUND in $DC"
                Add-Content -Path "C:\path\validemails.txt" -Value "$line : $DC"
                break
            }
            else {
                "$line not found in $DC"
            }
        }
    }

Upvotes: 0

Gabriel Luci
Gabriel Luci

Reputation: 40958

Use the Server parameter, but specify the port 3268 since that is the port used for the global catalog. The global catalog is the listing for your whole forest.

Get-ADUser -Filter "EmailAddress -like '$line'" -Server domain.com:3268

Where domain.com is the DNS name of any domain in your forest.

Here are the various ports used for Active Directory:

  • 389: LDAP - single domain only (the default if you don't specify anything)
  • 3268: Global Catalog - your whole forest
  • 636: LDAP over SSL
  • 3269: Global Catalog over SSL

Upvotes: 0

EDHCAH
EDHCAH

Reputation: 21

Try specifying the server (domain controller) for the other domains:

$DC = 'DC_name'
foreach($line in Get-Content C:\path\emails.txt) {
    if(Get-ADUser -Filter "mail -like '$line*'" -Server $DC ) {
        "$line is valid"
    }
    else {
        "$line is invalid"
    }
}

Upvotes: 2

Related Questions