Adding users to an Office365 tenant with remote Powershell

Have you got a list of users to add to Office365?
Don’t fancy adding them one by one from the portal?

This post is for you.

Azure AD and remote PowerShell are your friends when it comes to automating or semi automating many of the tasks you would normally undertake via the web portal.

The below script will take a CSV input and create each of the users in your chosen Office365 tenant. It will also assign a random password and create a CSV output containing the properties of the added users as well as the generated passwords.


#Function for selecting CSV (and consequently setting output path)

Function Get-FileName($initialDirectory)
[System.Reflection.Assembly]::LoadWithPartialName("") | Out-Null

$OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
$OpenFileDialog.Title = "Select User Input File"
$OpenFileDialog.initialDirectory = $initialDirectory
$OpenFileDialog.filter = "CSV (*.csv)| *.csv"
$OpenFileDialog.ShowDialog() | Out-Null

#O365 tenant admin credentials
$User = ""
$Pass = "userPassword"

$Cred = New-Object System.Management.Automation.PsCredential($User,(ConvertTo-SecureString $Pass -AsPlainText -Force))

#Connect to Azure AD
Connect-MsolService -Credential $Cred
$inputfile = Get-FileName "C:\"
$outputFolder = Split-Path -Parent $inputfile
$outputPath = -join ($outputFolder, "\NewUserResults.csv")

Import-Csv -Path $inputfile | foreach {New-MsolUser -DisplayName $_.DisplayName -FirstName $_.FirstName -LastName $_.LastName -UserPrincipalName $_.UserPrincipalName -UsageLocation $_.UsageLocation -LicenseAssignment $_.AccountSkuId} | Export-Csv -Path $outputPath

#Output users in Tenant (with license assigned)

Here is the CSV file that you need to populate with the users to add.


You will need to populate the script with credentials for a tenant administrator.

You may also need to enable running of unsigned scripts if you haven’t already or you will receive an error. This is quite easy, just run the following PowerShell command.

Set-ExecutionPolicy Unrestricted

You can find more information on Execution Policy on TechNet here.

Further Considerations

If you already have un-assigned licenses present in the Office365 tenant then it is possible to assign a license at the same time as adding the user with the -LicenseAssignment property.
This script could be easily modified to accept this as an additional column in the newUsers CSV.

The full Microsoft reference for creating user accounts with Office 365 PowerShell can be found here.

Share This:

Leave a Reply

Your email address will not be published. Required fields are marked *