Tuesday, October 14, 2014

Everyday Powershell - Part 29 - Add-SMTPAlias

It's funny. When you think about how many clicks you need to go through to add an SMTP alias to an Exchange mailbox... There's a lot of clicks! Or you could just use this function and be done in 5 seconds.

function Add-SMTPAlias{
    <# Add-SMTPAlias
    .SYNOPSIS Adds smtp alias to a given mailbox

    .DESCRIPTION

    .PARAMETER alias
    Users Alias

    .PARAMETER
    newsmtpaddress desired email alias

    .EXAMPLE
    Add-IPToSMTPRelay -alias someuser -newsmtpaddress someusersotheremail@someserver.com 
    #>

    [CmdletBinding()]
    param (
        [Parameter(mandatory=$true,ValueFromPipeline=$true)]
        $alias,
        [Parameter(mandatory=$true,ValueFromPipeline=$true)]
        [mailaddress]$newsmtpaddress
    )
    process{
        $emailaddresses = (get-mailbox $alias).emailaddresses
        $emailaddresses += $newsmtpaddress.ToString()
        try{
            Set-Mailbox $alias -EmailAddresses $emailaddresses -ErrorAction stop
        }
        catch{
            write-warning ("Problem setting email address " + $_)
        }
    }
}

5 minutes or 5 seconds, the choice is yours GUI fans. Maybe it's time to give in to the power of the shell?

2 comments:

  1. Your Try/Catch block probably won't really do anything. You need to include -ErrorAction stop. You can only catch terminating exceptions and -ErrorAction Stop will do that if there is a problem. Some cmdlets automatically throw terminating exceptions and Set-Mailbox might be one of them. But you'd be better off getting in the habit of using ErrorAction in a Try block.

    ReplyDelete
    Replies
    1. Thanks Jeff! I've been caught by neglecting -erroraction stop before. "Hmm why didn't the exception get caught?"... You are right I should make it a habbit to include it

      Delete