Wednesday, August 29, 2007

Changing SMTP primary address (Exchange 2007)

 
This function will list all Email addresses for a given user and allow you to choose (interactively) a new default SMTP address. Use the -Verify switch to emit the new default address.
 
 

function Set-PrimaryEmailAddress{
    param([string]$name, [switch]$verify)
    # filters only smtp addresses
    $smtp =  @((get-Mailbox -Identity $name).EmailAddresses | where {$_.PrefixString -eq "SMTP"})

    for($i=0;$i -lt $smtp.length;$i++){
        if($smtp[$i].IsPrimaryAddress){
            # colorize default address in green
            write-host "$($i+1). $($smtp[$i].SmtpAddress)" -b black -f green;
        } else {
            write-host "$($i+1). $($smtp[$i].SmtpAddress)";
        }
    }
    [int]$num=0;
    $choice=read-host "`nChoose new primary SMTP address for <$name>?"
    if((-not [int]::TryParse($choice,[ref]$num) -or $num -gt $smtp.length)){
        write-host "ERROR: Invalid input." -foreground red -background black;
        exit;       
    } else {
        # you need to assign $false to -EmailAddressPolicyEnabled otherwise an error occurs
        #Set-Mailbox : This command will clear the PrimarySMTPAddress property.
        #Because EmailAddressPolicyEnabled is set to true, this action is not allowed.
        set-mailbox -Identity $name -EmailAddressPolicyEnabled:$false -PrimarySmtpAddress $smtp[$num-1];
        if($verify) {(get-Mailbox -Identity $name).PrimarySmtpAddress.ToString()}
    }
}

 

Usage:

>> Set-PrimaryEmailAddress "administrator" -verify

 
 


No comments: