Thursday, 10 March 2011

Converting Mail User to Mail Enabled User With Mail Forwarding to External EMail Address (Exchange 2007)

This snippet of code will convert a MAIL USER to MAILBOX enabled user and it will store and forward emails to his external email address.


**  The code below creates a dummy mail user Greg Perth and converts it to MAIL ENABLED USER **

$pwd = Read-Host "Enter Password" -Assecurestring

New-Mailuser -Name "Greg Perth" -ExternalEmailAddress "Greg.Perth@hotmail.com" -OrganizationalUnit "Perth" -Password $pwd -UserPrincipalName "Greg.Perth@mycompanydomain.com.au" -SamAccountName "Greg.Perth"
 

$obj = Get-MailUser -id "Greg Perth"
Disable-MailUser -id "Greg Perth" -confirm:$false


  $timer = [diagnostics.stopwatch]::startnew()
  $erroractionpreference = "silentlycontinue"
  $mailboxsuccess = $false
  while (($timer.elapsed.totalseconds -lt 900) -and (!($mailboxsuccess)))
   {
   $error.clear()

   New-MailContact -Name $obj.Name -ExternalEmailAddress $obj.ExternalEmailAddress -OrganizationalUnit "PerthContacts" -Verbose:$false

   if($error.count -eq 0)
    {
    write-host "Mail Contact successfully created"
    $mailboxsuccess = $true
    }
   else
    {
    write-host "." -nonewline
    start-sleep -s 30
    }
  }
  $timer.stop()
  $erroractionpreference = "continue"
  $secs = "{0:N2}" -f ($timer.elapsed.totalseconds)
  write-host "Mail Contact Process ran for: $secs seconds."

Enable-Mailbox -id "Greg Perth" -Database "Mailbox Database" -Verbose:$false

Set-Mailbox -id "Greg Perth" -ForwardingAddress $obj.DistinguishedName  -DeliverToMailboxAndForward:$true -Verbose:$false
 

write-host "*** *** **** "
write-host "Successfully Converted Mail enabled User to Mailbox User with external mail forwarding."
write-host "*** *** ****"

No comments:

Post a Comment