≡ Menu

Checking if an Email Address is In-Use within a PowerShell script

I was asked recently for a good way to check if an email address is already in use within an Exchange 2010 PowerShell script. My initial approach was simply to use the Get-Mailbox cmdlet. After all, this cmdlet accepts an SMTP address as input, and if you get an error using this cmdlet with a particular SMTP adress, you then know that address is not in use. In practice, that might look like this:

if (!(Get-Mailbox 'dave@test.com' -ErrorAction SilentlyContinue)) {
    #not being used, lets continue

The if statement checks to see if Get-Mailbox returns a value, and ignores any errors since the ErrorAction is set to silently continue. If we get a result, we move on and run whatever code is needed.

That’s a nice idea, but there’s a major flaw with this approach. There are multiple recipients types to take into consideration: mailboxes, distribution groups, mail contacts, etc. For a truly comprehensive check, we need something to test all of these recipient types.

I originally wrote a fairly lengthy advanced function switch over each of the Get-* recipient cmdlets to check each type. Fortunately, there’s a much easier way to do this. Simply use the Get-Recipient cmdlet.

if (!(Get-Recipient 'dave@test.com' -ErrorAction SilentlyContinue)) {
     #not being used, lets continue

This is a great example of how simple things can be in PowerShell, even though a lot of times our first approach is an overly complicated solution. Big thanks to DJ for pointing out this out and reminding me about this cmdlet. Now if you’ll excuse me, I’m off to the drug store to pick up some Ginkgo biloba.

1 comment… add one

  • Martin May 20, 2014, 7:15 am

    Perfect. That’s what I was looking for. Thank you very much!!!

Leave a Comment