Thursday, 3 October 2013

Exchange 2010 Powershell: Create external SMTP contacts and import in to specific OU's from CSV

Requirements:

1. Import 3000 contacts from CSV for a number of Companies.

2. Each contact is to go in to an OU in AD of the name of the Company to which they belong.

3. The name of the contact should also include the name of the Company in brackets, so as it appears in the address field in Outlook users can easily see which company the contact is from e.g. Dave Smith (Te5t).

4. The Alias needs set be manually, since it will not accept the brackets it will convert them to question marks. Spaces are also not allowed, so we'll get the Name and remove the space character.
5. Also to be imported in to the contact fields is the company they work for and their job title.


SO... here's Testcontacts.csv

Company,Name,Firstname,Lastname,Job,Email
Te5t,Dave Smith,Dave,Smith,CEO,ceo@testcompany.com
T3st,Jenny Jones,Jenny,Jones,PA,pa@testcompany.com


"Company" is also to be the name of the OU in AD. So I've created two OU's called "Te5t" and "T3st". Here's the first Powershell lines:

$contacts = Import-CSV c:\contacts\testcontacts.csv

$contacts | foreach { New-MailContact -Name "$($_.Name) ($($_.Company))" -Alias $_.Name.Replace(" ","") -FirstName $_.firstname -LastName $_.lastname -ExternalEmailAddress $_.email  -OrganizationalUnit $_.Company -whatif}

I run this first with the -whatif, any existing entries should be highlighted in red. I'll note these down and delete these entries before proceeding. Once the duplicated have dealt with I rerun this minus the -whatif.

$contacts | ForEach {Set-Contact $_.Name -Company $_.School -Title $_.Title -whatif}

Bingo! Time for the real deal...