28 April 2017

Create new AD User with Remote Mailbox | Office 365 Hybrid

I recently had a client who had a Hybrid Office 365 who required a set of users to be created, and Office 365 mailboxes created at hte same time.  Whilst I could have had a script to create the users, then go through and add mailboxes to them, I decided that it would be better to smash it all in one hit.

Thanks to my colleague Gareth for writing this script

The following process is comprised of two steps.


  1. Run a script that references a CSV File
  2. A CSV file that has all the relevant information in it
In this case my CSV file had the following:


The BackupEmail was put there at the Client's request.  It was just an area to put the user's personal email address within the AD object.  

The script used is the following, which needs to be saved as CreateUsers.csv.  Note the bold areas which are the variables that have been included.


$Users = Import-Csv -Path "C:\Userlist.csv"
$OU = "OU=Sub-OU,OU=Parent-OU,DC=DOMAIN,DC=com,DC=au"     
foreach ($User in $Users)           
{           
    $Displayname = $User.Firstname + " " + $User.Lastname           
    $UserFirstname = $User.Firstname           
    $UserLastname = $User.Lastname           
    $SAM = $User.Username         
    $UPN = $User.Firstname + "." + $User.Lastname + "@domain"        
    $Password = "<insertpassword>" 
    $Mobile = $User.Mobile
     $remoterouting = "smtp:" + $UPN
     $Notes = $User.BackupEmail
    New-ADUser -Name "$Displayname" -DisplayName "$Displayname" -SamAccountName $SAM -UserPrincipalName $UPN -GivenName "$UserFirstname" -Surname "$UserLastname" -AccountPassword (ConvertTo-SecureString $Password -AsPlainText -Force) -Enabled $true -Path "$OU" -ChangePasswordAtLogon $false –PasswordNeverExpires $true -MobilePhone $Mobile -HomePhone $Notes
    Enable-RemoteMailbox $SAM -RemoteRoutingAddress $remoterouting
}

Save the script as well as the .csv file into the same location, then run the script through Exchange Management Shell.

This will create the user account and will also create the Office 365 Mailbox which can be viewed from either Exchange On Prem, or the O365 Tenant.  Remember that it takes a bit of time for Azure AD Connect to sync all the AD objects as well.  It might help to force an Azure AD Connect sync.

The last step you will need to do is to assign an Office 365 license to that particular user, or users.

3 comments: