Wednesday, June 3, 2015

PowerShell function | Add or Remove email address | Exchange



Hi,

Today, I share with you my code to build a function to add or remove an email address with PowerShell. Feel free to use and modify my code. If you made some improvements, please share it.

Thanks!
 <#  
 .Synopsis  
   Connect a remote session to the Exchange 2010 server.  
   Add or remove an email address for an account (user).  
 .DESCRIPTION  
   This cmdlet need to have access to the cmdlet of Exchange.  
   Its script to be used with Exchange 2010.  
   Version 1.1  
   Script by Jeremie Lauzier - Network Administrator, 2015-06-02  
 .EXAMPLE  
   Add an email address to the account Oliver Queen  
   Set-XXXEmailAddress -accountmodify queeno -emailaddress arrow@greenarrow.com -choice Add  
 .EXAMPLE  
   Remove an email address to the account Oliver Queen  
   Set-XXXEmailAddress -accountmodify queeno -emailaddress arrow@greenarrow.com -choice Remove  
 .EXAMPLE  
   All parameters are mandatory. So just type Set-XXXEmailAddress and field choice one at a time.  
 #>  
 function Set-XXXEmailAddress  
 {  
   [CmdletBinding()]  
   [OutputType([int])]  
   Param  
   (  
     # Define the account to modify  
     [Parameter(Mandatory=$true,  
           ValueFromPipelineByPropertyName=$true,  
           Position=0)]  
     $accountmodify,  
     # Define the email adress to add or remove  
     [Parameter(Mandatory=$true)]  
     $emailaddress,  
     # Add or remove address  
     [Parameter(Mandatory=$true)]  
     [ValidateSet("Add", "Remove")]  
     $choice  
   )  
   Begin  
   {  
   $exchsession=New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://servername.domain.abc/powershell  
   Import-PSSession $exchsession -AllowClobber  
   }  
   Process  
   {if ($choice -eq "Add")  
    {  
      Set-Mailbox $accountmodify -EmailAddresses @{add=$emailaddress}  
    }  
    if ($choice -eq "Remove")  
    {  
      Set-Mailbox $accountmodify -EmailAddresses @{remove=$emailaddress}  
    }  
    Get-Mailbox -Identity $accountmodify | Select -expand emailaddresses alias  
   }  
   End  
   {  
   Remove-PSSession $exchsession  
   }  
 }  

No comments:

Post a Comment