Powershell 2 and Exchange: Find conflicting objects

I am new to powershell and Exchange so go easy on me if this comes out sounding confusing.

I need to generate a list of every possible email address in our environment (tens of thousands) that will cause the following code to error out due to an object that already exists with that email address as one of its key properties:

New-MailContact -Name $email                                  `
                -ExternalEmailAddress $email                  > $null

I have tried iterating through all entries returned from get-mailcontact, storing every email address from the 'EmailAddresses' collection, but now I believe I also need to extract all possible email addresses from User objects. I've gotten to the point where I'm thinking there's an easier, possibly one-shot way, to do this.

What is the easiest way in PS 2 to accomplish this? Is there a way to guarantee that if an email address IS in the list, New-MailContact will fail with a duplicate error, and if the email address is NOT in the list, then we are guaranteed that New-MailContact will not produce an error due to duplicates. (It may produce other errors, but not because an object already is associated with this address.)

Thanks!


Solution 1:

I believe you could just grab every object out of your Active Directory that has a non-empty ProxyAddresses collection and then filter out for the SMTP addresses (excluding SIP and X400) -

Get-ADObject -Properties ProxyAddresses -Filter 'ProxyAddresses -gt 0' | select ProxyAddresses | %{$_.ProxyAddresses} | where{$_.ToUpper().StartsWith('SMTP:')}