Powershell – Creating Active Directory User Accounts: with an Office 365 mailbox

Most IT admins know what a pain it is to set up Active Directory user accounts, especially when you need to setup a corresponding 365 mailbox.

Hopefully, this script is going to help you!

I’m going to guide you though using Powershell to create an Active Directory account, with a licenced Office 365 mailbox (in a hybrid Exchange 2013 environment).

I’m assuming you’re executing this script from an Admin Powershell prompt, on a Domain joined PC (It maybe useful for you to run this script in Powershell ISE).

This script will:

  • Create an Active Directory user account + allow you to assign a user password (securely).
  • Complete AD account details such as telephone number and address (useful if you are using my email signature script guide).
  • Create an Office 365 mailbox (this script assumes that you are running in Exchange hybrid mode (i.e. your business also has an on Premise Exchange server).
  • Turn on litigation hold enabled (for this to work, you will need the correct licences, ie: E3).
  • Assign a 365 licence (I’m also assigning an ATP licence, Windows 10 licence and PowerBI standard licence).

You’ll need to prepare your IT admin PC. Perform the following steps:

For the final part of our prep, launch an admin Powershell prompt and run the following command:

set-executionpolicy remotesigned

Script starts here:

The first part of the script brings in the Active Directory powershell modules.

#Installs AD modules
import-module activedirectory

The next part of the script asks for the user details (I’ve yet to implement error capturing in this section; so if you don’t have the relevant info, press space to register some input before pressing enter).

Make sure details are accurate, and if you are using my email signature script, it will be just as important to enter Job Title, Phone number etc.  if not; just comment those sections out using: #

I’ve also set the script to check for location.  Useful if you have multiple offices and want to pre-set different office addresses & security groups.

Write-host "Please complete the following questions, Ensure spelling and case are accurate"

$First=Read-Host 'Enter First Name'

$Last=Read-Host 'Enter Last Name'

$Title=Read-Host 'Enter Job Title'

$EmployeeID=Read-Host 'Enter the EmployeeID. Press Space then Enter if information is not available'

$Mobile=Read-Host 'Enter the Mobile Phone Number. Press Space then Enter if information is not available'

$Department=Read-Host 'Enter the users department. Press Space then Enter if information is not available'

$DirectDial=Read-Host 'Enter the users direct dial number. Press Space then Enter if information is not available'

$InternalExtension=Read-Host 'Enter the users internal extension number. Press Space then Enter if information is not available'

$Qualifications=Read-Host 'Enter any relevant qualifications. Press Space then Enter if information is not available'

$Location=Read-Host 'Enter Location: Exeter, Truro, Plymouth or Bristol'

 

Using the data captured above, the script builds up some variables needed to create a user account.

The script is configured to convert email addresses to lowercase (for cosmetic purposes).

Using host location information, the relevant address information will be populated.

#Pre-set fields generic to all users regardless of location

$FirstLower=$First.ToLower()
$LastLower=$Last.ToLower()

$SAMAccountName=$FirstLower+'.'+$LastLower

$DisplayName=$First+' '+$Last

$Mailnickname=$First+$Last

$UserPrincipalName=$FirstLower+'.'+$LastLower+'@contoso.co.uk'

$RemoteRoutingAddress=$FirstLower+'.'+$LastLower+'@contoso.onmicrosoft.com'

$ProxyEmailAddress=$FirstLower+'.'+$LastLower+'@contoso.onmicrosoft.com'

$EmailAddress=$FirstLower+'.'+$LastLower+'@contoso.co.uk'

#This maybe of use if the company domain has changed but is still used for mailflow.
$oldEmailAddress=$FirstLower+'.'+$LastLower+'@tailspintoys.co.uk'

$Company="Contoso Ltd"

$WWWHomePage="www.contoso.co.uk"

#This section prompts you to enter a password - this is the users initial password
$password=Read-Host "Enter Users Password" -AsSecureString

#Custom fields - dependent on office location
#Make sure the $Path location below is sync'd to office 365 - this is setup in the sync service manager installed on your domain controller

If ($Location -eq 'Exeter')
{
$Path="OU=Exeter,DC=contoso,DC=local"
$OfficePhone="01234 567890"
$Fax="01234 567890"
$StreetAddress="Street Address 1"
$POBox="Street Address 2"
$City="Exeter"
$State="Devon"
$PostalCode="EX Postcode"
}

ElseIf ($Location -eq 'Plymouth')
{
$Path="OU=Win10,OU=Plymouth,DC=contoso,DC=local""
$OfficePhone="01234 567890"
$Fax="01234 567890"
$StreetAddress="Street Address 1"
$POBox="Street Address 2"
$City="Plymouth"
$State="Devon"
$PostalCode="PL Postcode"
}

ElseIf ($Location -eq 'Truro')
{
$Path="OU=Truro,DC=contoso,DC=local""
$OfficePhone="01234 567890"
$Fax="01234 567890"
$StreetAddress="Street Address 1"
$POBox="Street Address 2"
$City="Truro"
$State="Cornwall"
$PostalCode="TR Postcode"
}

ElseIf ($Location -eq 'Bristol')
{
$Path="OU=Win10,OU=Bristol,DC=contoso,DC=local""
$OfficePhone="01234 567890"
$Fax="01234 567890"
$StreetAddress="Street Address 1"
$POBox="Street Address 2"
$City="Bristol"
$State="Bristol"
$PostalCode="BS Postcode"
}

Else {

write-host "Incorrect Location Entered; exiting script"
start-sleep -milliseconds 10000
exit
}

 

Now, the AD user account is created.

#Create user section - this builds the AD account using the fields above
New-ADUser -SAMAccountName $SAMAccountName -name $DisplayName -GivenName $First -Surname $Last -UserPrincipalName $UserPrincipalName -DisplayName $DisplayName -Department $Department -Path $Path -Company $Company -EmployeeID $EmployeeID -Fax $Fax -OfficePhone $OfficePhone -HomePhone $DirectDial -Mobile $Mobile -StreetAddress $StreetAddress -City $City -POBox $PObox -State $State -PostalCode $PostalCode -ChangePasswordAtLogon -OtherAttributes @{title=$title;mail=$EmailAddress;wwwHomePage=$WWWHomePage;c="GB";co="United Kingdom";ipPhone=$InternalExtension;info=$qualifications}

#This section adds the users email addresses. The primary email address should be SMTP in caps, secondary addresses in lowercase.
Set-ADUser -identity $SAMAccountName -Add @{ProxyAddresses="SMTP:$EmailAddresses"}
Set-ADUser -identity $SAMAccountName -Add @{ProxyAddresses="smtp:$OldEmailAddress"}
Set-ADUser -identity $SAMAccountName -Add @{ProxyAddresses="smtp:$ProxyEmailAddresses"}
#pauses the script to allow AD to replicate
start-sleep -milliseconds 5000

 

This part of the script adds the user into the company’s generic security groups.

It also uses  the address information to add the user into any relevant group based on location. The group name cab be found under attribute editor, CN.

#Adds user into standard company groups
 Add-ADGroupMember -Identity "Generic AD Security Group 1 SG" -Members $SAMAccountName
 Add-ADGroupMember -Identity "Generic AD Security Group 1 SG" -Members $SAMAccountName
 Add-ADGroupMember -Identity "Generic AD Security Group 1 SG" -Members $SAMAccountName

#Adds user into location specific security groups
If ($Location -eq 'Exeter')
 {
Add-ADGroupMember -Identity "Exeter Security Group" -Members $SAMAccountName

}

ElseIf ($Location -eq 'Plymouth')
 {
Add-ADGroupMember -Identity "Plymouth Security Group" -Members $SAMAccountName
 }

ElseIf ($Location -eq 'Truro')
 {
Add-ADGroupMember -Identity "Truro Security Group" -Members $SAMAccountName
 }

ElseIf ($Location -eq 'Bristol')
 {
Add-ADGroupMember -Identity "Bristol Security Group" -Members $SAMAccountName

}

Start-sleep -milliseconds 5000

 

This part of the script uses the password you previously set; then enables the AD account (AD account cannot be enabled without a password).

Set-ADAccountPassword -identity $SAMAccountName -NewPassword $password -Reset

Start-sleep -milliseconds 5000

Enable-ADAccount -Identity $SAMAccountName

 

Next, we’re going to get our AD server (with Microsoft AD Connect Sync Service installed) to perform a Delta Sync from AD to Office 365. This will register the new user account in the 365 portal.

#This section forces and AD to 365 Delta sync from the domain controller, then pauses the script to make sure the sync has completed.

Invoke-Command -Computer Contoso-AD1 -Scriptblock {Start-ADSyncSyncCycle -PolicyType Delta}

start-sleep -milliseconds 10000

 

Mail routing functionality breaks if you try and create a mailbox directly in 365, rather than using Exchange 2013 – we will need to create a 365 mailbox though Exchange Powershell.

However; we don’t want to have to run commands directly on our Exchange server, so we’re going to create an Exchange Powershell session from our IT admin PC and then create the 365 mailbox.

#This part of the script connects to a Powershell session via the on-prem exchange 2013 server (hybrid environment).

$Session = New-PSSession –ConfigurationName Microsoft.Exchange –ConnectionUri http://contoso-mbx1/powershell -Authentication Kerberos

Import-PSSession $Session -DisableNameChecking -AllowClobber


#This part creates the Office365 mailbox though the on-premise exchange 2013 server (hybrid mode)

Enable-RemoteMailbox -identity $SAMAccountName –remoteroutingaddress $RemoteRoutingAddress

#This bit turns on mailbox archiving - check your licencing arrangement!
Enable-RemoteMailbox $SAMAccountName -Archive

#Forces the script to pause whilst 365 account is setup

start-sleep -milliseconds 10000

Now, we’re connecting to our 365 portal. This is where you will be prompted to login to 365.

#Connects to Office 365 portal. Will prompt for valid admin credentials. Manually running $AccountSKU Will report back number of licences used / available.

import-module MsOnline
Connect-MsolService
$AccountSKU = Get-MsolAccountSKU
$AccountSKU
$UserLicence = Get-MsolUser -UserPrincipalName $UserPrincipalName

Next, the script sets the users location – in this case GB (Great Britain). Change Contoso to your company name (ie the bit before onmicrosoft.com)

We’re also assigning:

  • Office 365 E3 licence
  • Advanced Threat Protection licence
  • PowerBI Standard (free) licence
  • Windows 10 Enterprise licence
#This sets the users location; needed before licences can be assigned
 Set-MsolUser -UserPrincipalName $UserPrincipalName -UsageLocation GB

Write-host "Assigning licences: Office 365 E3, MS ATP, Windows 10 and PowerBi Std"
 
 Set-MsolUserLicense -UserPrincipalName $UserPrincipalName -AddLicenses "Contoso:ENTERPRISEPACK"

 Set-MsolUserLicense -UserPrincipalName $UserPrincipalName -AddLicenses "Contoso:ATP_ENTERPRISE"

 Set-MsolUserLicense -UserPrincipalName $UserPrincipalName -AddLicenses "Contoso:POWER_BI_STANDARD"

 Set-MsolUserLicense -UserPrincipalName $UserPrincipalName -AddLicenses "Contoso:WIN10_PRO_ENT_SUB"

start-sleep -milliseconds 5000

 

This part of the script closes our connection to the on-premise Exchange server.

#Cleans up Exchange on premise script session

Remove-PSSession $Session

 

This section turns on litigation (legal) hold. You’ll need the correct licences (ie E3) so check this before continuing.  If you’re using incompatible licences, remove or comment out this section.

$Credential = Get-Credential

$ExchangeSession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri "https://outlook.office365.com/powershell-liveid" -Credential $credential -Authentication "Basic" -AllowRedirection

Import-PSSession $ExchangeSession

start-sleep -milliseconds 5000

Get-Mailbox -identity $SAMAccountName | Set-Mailbox -LitigationHoldEnabled $True

start-sleep -milliseconds 5000

#Cleans up connection to 365 servers
Remove-PSSession $ExchangeSession

 

Once the script completes; you’ll be advised that Microsoft can take 30 minutes to prepare the mailbox. You may find that you are able to login to portal.office.com but the webmail button will be broken until the mailbox setup has completed – even if it appears available in the admin portal.

write-host "Allow 30 minutes for Microsoft / Office 365 to create the mailbox"

start-sleep -milliseconds 10000
exit

 

That concludes the AD script! Hopefully you have found it of some use, and save some time in your busy IT environment.

As I find improvements, I’ll update the guide.

TSN.

Advertisements

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s