21 February 2017

Import Mail Contacts into Office 365 from CSV File | PowerShell

This blog post has been created as I have recently needed to upload hundreds of Mail Contacts into Office 365.

1. Create a CSV file which has the following columns:

2. Populate the CSV file with the required contents.  Name will be their Display Name, so there cannot be any spaces etc.  Usually with this I will populate the FirstName & LastName and then have the following for Name:
This will combine the first name and the last name and remove any spaces etc.  Then just drag this down for all the users and it will populate for everyone.

3. Save this file as ImportContacts.csv
4. Open PowerShell ISE and add the following contents
(change the bold section to reflect where you've saved your ImportContacts CSV file).

#Connect To Exchange Online 
$UserCredential = Get-Credential 
$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri https://outlook.office365.com/powershell-liveid/ -Credential $UserCredential -Authentication Basic -AllowRedirection 
Import-PSSession $Session

#Function to pick the CSV File 
Function Get-FileName($initialDirectory) 

[System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) | 

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog 
$OpenFileDialog.initialDirectory = $initialDirectory 
$OpenFileDialog.filter = “All files (*.*)| *.*” 
$OpenFileDialog.ShowDialog() | Out-Null 
} #end function Get-FileName 
#Command To Launch Function and store it in the variable 
$PathToCSV = Get-FileName -initialDirectory "C:\Users\adam.arkwright\Desktop\ImportContacts.csv"

#Commands to import CSV file to contacts then export the contact list for comparison 
Import-Csv $PathToCSV | %{New-MailContact -Name $_.Name -DisplayName $_.Name -ExternalEmailAddress $_.ExternalEmailAddress -FirstName $_.FirstName -LastName $_.LastName} 
Get-MailContact | Select DisplayName,ExternalEmailAddress,FirstName,LastName | Out-GridView 
Get-MailContact | Select DisplayName,ExternalEmailAddress | Export-Csv "C:\Users\adam.arkwright\Desktop\ExportedContacts.csv"

5. Save this as ImportContacts.ps1 somewhere easily accessible. 
6. Open PowerShell as administrator and run ImportContacts.ps1

This will then ask you for your Office 365 Username and Password.  Make sure you use the administrator credentials.  If there's any issues, you may find a File Explorer windows pop up.  If this happens, simply navigate to where you've saved the .csv file and double click on it.  Then it will go through and start importing all the contents into your Office 365 tenant.