Add contacts and groups to Office 365 in bulk using Powershell

There comes a time, especially working in schools, where you have to add a lot of contacts and groups at once to Office 365.

This is where Powershell comes in. What would take you days through the Office 365 admin page will take you an hour or two using Powershell.

Preparing Contacts

The first thing you need to do is prepare a CSV for Powershell to pull contact data from. Each contact needs an email address and a name as follows:

firstperson@gmail.comJohn SmithJohnSmith
secondperson@hotmail.comJane DoeJaneDoe
Create the file in Excel and save it as a CSV file to your C:\ drive. It doesn’t have to be the C:\ drive but that just makes it clearer when dealing with file paths.

Connecting to Powershell

Now you need to connect to Exchange Online using a Powershell session but first you want to enable the running of scripts. Open Powershell and type:

Set-ExecutionPolicy RemoteSigned
$UserCredential = Get-Credential

Enter your Office 365 Admin details at the prompt. Then continue below.

$Session = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri -Credential $UserCredential -Authentication Basic -AllowRedirection
Import-PSSession $Session

You should now be connected to your Exchange Online account. Enter the following to import your Contacts CSV file. The below code makes the assumption that your first is in the C:\ drive and is called contacts.csv. Rename as appropriate.

Import-Csv C:\contacts.csv|%{New-MailContact -Name $_.Name -DisplayName $_.Name -ExternalEmailAddress $_.ExternalEmailAddress -FirstName $_.FirstName -LastName $_.LastName}

This completes the importing of new contacts into Exchange Online.

Bulk Importing into Groups

If it’s a new group you can create it in Powershell:

New-DistributionGroup -Name "GROUP_NAME" -Type "Security"

Then create a CSV file for each group you need:

John Smith
Jane Doe
All this needs is one column called Name with the names pasted from your earlier contacts CSV.

Back in Powershell enter the following:

Import-CSV C:\FILE_NAME.csv | ForEach {Add-DistributionGroupMember -Identity "GROUP_NAME" -Member $_.Name}

Replacing FILE_NAME with the filename of your CSV file AND GROUP_NAME with the desired group.

And that’s it. Please do comment below if you know of any further ways to reduce the time it takes to create groups and contacts in bulk.

Leave a Reply

Your email address will not be published.