PowerShell – Create new AD user account, Exchange mailbox and add to Lync Pool


The below script presents a simple means of setting up a user in Active Directory, Exchange and Lync in one go.


###############################################################################
#                                                                             #
# ****************** CREATED BY MAURICE DALY ON 18/12/2013 ****************** #
#                                                                             #
# Create user account, exchange mailbox and lync account                      #
#                                                                             #
# Version 1.0                                                                 #
#                                                                             #
# ****************** UPDATED BY MAURICE DALY ON 09/01/2014 ****************** #
#                                                                             #
# Version 2.0 - All modules are imported automatically with detection for     #
#               Active Directory, Exchange & Lync environments. Notification  #
#               feature also added for predetermined admin mail account       #
#               Added OU location menu.                                       #
#                                                                             #
# THIS SCRIPT IS USED AT YOUR OWN RISK. I ACCEPT NO RESPONSIBILITY FOR ANY    #
# ISSUES ARRISING FROM IT                                                     #
#                                                                             #
###############################################################################


cls

Write-Host "**************** PLEASE ENTER YOUR SECURITY DETAILS ****************"
$Credential = Get-Credential -Credential "$env:USERDOMAIN\$env:USERNAME"
$DC = $env:LOGONSERVER.Substring(2)

#Initiate Remote PS Session to local DC
$ADPowerShell = New-PSSession -ComputerName $DC -Authentication Negotiate -Credential $Credential

# Import-Module ActiveDirectory
Invoke-Command -Session $ADPowerShell -scriptblock {import-module ActiveDirectory}
Import-PSSession -Session $ADPowerShell -Module ActiveDirectory -AllowClobber -ErrorAction Stop

# Retrieve AD Details
$ADDetails = Get-ADDomain
$Domain = $ADDetails.DNSRoot
$ExchangeServer = Get-ADObject -Filter "(ServicePrincipalNAme -like 'IMAP*')" -SearchBase (Get-ADDomain).DistinguishedName.tostring()  -Properties ServiceDNSName, ServiceClassName | where name -NotLike *SDK* | ForEach-Object {Write-Output $($_.Name + "." + $Domain)} | Get-Random

cls
Write-Host "********************* NEW USER CREATION SCRIPT *****************"
Write-Host ""
Write-Host "Please enter the following required details:"
$FirstName = read-host "Firstname"
$FirstName = $FirstName.substring(0,1).toupper()+$FirstName.substring(1).tolower()   
$Surname = read-host "Surname"
$Surname = $Surname.substring(0,1).toupper()+$Surname.substring(1).tolower()  
$FirstInitial = $FirstName.Substring(0,1)

# Select Office Location
$OUChoice = ""
 while ($OUChoice -notmatch "[1|2|3|4|5]"){
     Write-Host ""
     Write-Host "[1] Office 1" 
     Write-Host "[2] Office 2"
     Write-Host "[3] Office 3"
     Write-Host "[4] Office 4"
     Write-Host "[5] Office 5"
     Write-Host ""
     $OUChoice = read-host "Please select the office location for $FirstName $Surname"
     }

if ($OUChoice -eq "1"){$ADPath = "OU=Office1,DC=YOUR,DC=DOMAIN"}
if ($OUChoice -eq "2"){$ADPath = "OU=Office2,DC=YOUR,DC=DOMAIN"}
if ($OUChoice -eq "3"){$ADPath = "OU=Office3,DC=YOUR,DC=DOMAIN"}
if ($OUChoice -eq "4"){$ADPath = "OU=Office4,DC=YOUR,DC=DOMAIN"}
if ($OUChoice -eq "5"){$ADPath = "OU=Office5,DC=YOUR,DC=DOMAIN"}


# Detect if username already exists and create AD account
Write-Host -ForegroundColor Green "Creating new active directory user accounnt for $Firstname $Surname"
$ADAccountName = ($Surname + $FirstInitial)
$UserCheck = Get-ADUser -LDAPFilter "(sAMAccountName=$ADAccountName)"
If (($UserCheck) -eq $null)
 {
    write-host -ForegroundColor Green "Active Directory user account created"
    New-ADUser -DisplayName:($FirstName + " " + $Surname) -GivenName:$FirstName -Name:($FirstName + " " + $Surname) -Path:$ADPath -SamAccountName:$ADAccountName -Server:$DC -Surname:$Surname -Type:"user" -UserPrincipalName:($ADAccountName + "@" + $Domain) -Description:($Surname + $FirstInitial) -AccountPassword:(ConvertTo-SecureString "Secret123!" -AsPlainText -Force) -Enabled:$true
    Set-ADAccountControl -AccountNotDelegated:$false -AllowReversiblePasswordEncryption:$false -CannotChangePassword:$false -DoesNotRequirePreAuth:$false -Identity:$ADAccountName -PasswordNeverExpires:$false -Server:$DC -UseDESKeyOnly:$false
 }
 Else
 {
    $ADAccountName = Read-Host "The automatically generated username for $FirstName $Surname alreay exists. Please enter an alternative username" 
    New-ADUser -DisplayName:($FirstName + " " + $Surname) -GivenName:$FirstName -Name:($FirstName + " " + $Surname) -Path:$ADPath -SamAccountName:$ADAccountName -Server:$DC -Surname:$Surname -Type:"user" -UserPrincipalName:($ADAccountName + "@" + $Domain) -Description:$ADAccountName -AccountPassword:(ConvertTo-SecureString "Secret123!" -AsPlainText -Force) -Enabled:$true
    Set-ADAccountControl -AccountNotDelegated:$false -AllowReversiblePasswordEncryption:$false -CannotChangePassword:$false -DoesNotRequirePreAuth:$false -Identity:$ADAccountName -PasswordNeverExpires:$false -Server:$DC -UseDESKeyOnly:$false
 }


# Require password change on log on
Set-ADUser -ChangePasswordAtLogon:$true -Identity:$ADAccountName -Server:$DC -SmartcardLogonRequired:$false

# Exchange Mailbox creation
Write-Host -ForegroundColor Green "Creating new Microsoft Exchange mailbox for $Firstname $Surname"
$ExchangePowerShell = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://$ExchangeServer/Powershell
Import-PSSession $ExchangePowerShell -AllowClobber | Out-Null

If ($FirstInitial -ge "A") { $MailboxStore = "Mailboxes A-C" }
If ($FirstInitial -ge "D") { $MailboxStore = "Mailboxes D-J" }
If ($FirstInitial -ge "K") { $MailboxStore = "Mailboxes K-M" }
If ($FirstInitial -ge "N") { $MailboxStore = "Mailboxes N-R" }
If ($FirstInitial -ge "S") { $MailboxStore = "Mailboxes S-Z" }

Enable-Mailbox -Identity $ADAccountName -Alias $ADAccountName -Database $MailboxStore -RetentionPolicy 'YOUR Retention Policy' | Out-Null

Write-Host -ForegroundColor Green Yellow "Waiting 10 seconds for Exchange details to apply to Active Directory"
sleep -Seconds 10

# Lync Registrar
$LyncServer = Get-ADObject -Filter "(ServicePrincipalNAme -like 'SIP*')" -SearchBase (Get-ADDomain).DistinguishedName.tostring()  -Properties ServiceDNSName, ServiceClassName | ForEach-Object {Write-Output $($_.Name + "." + $Domain)}
$LyncRegistrarPool = $LyncServer

# Lync Module Import
$LyncPowerShell = New-PSSession -ConnectionUri https://$LyncServer/OCSPowerShell -Credential $Credential
Import-PSSession $LyncPowerShell -AllowClobber | Out-Null

# Lync Add User
Write-Host -ForegroundColor Green "Creating new Lync account for $Firstname $Surname"
Enable-CsUser -Identity $ADAccountName -RegistrarPool $LyncRegistrarPool -SipAddressType EmailAddress

# Notification variables
$ExchangeSMTP = "YOUR EXCHANGE SMTP SERVER"
$CreatedBy = Get-ADUser "$env:username" -properties Mail

# Notify Admin

$msg = new-object Net.Mail.MailMessage
$smtp = new-object Net.Mail.SmtpClient($ExchangeSMTP)
$msg.From = "$($CreatedBy.Mail)"
$msg.To.Add("Administrator@your.domain")
$msg.subject = "New User Account Created"
$msg.body = "$($CreatedBy.Name) has created a new user account for $FirstName $Surname." 
$msg.priority = [System.Net.Mail.MailPriority]::Low
$smtp.Send($msg)

Write-Host -ForegroundColor Green "Waiting 10 seconds for Lync details to apply"
sleep -Seconds 10

# Confirm User Account Creation
cls
Write-Host -ForegroundColor Green "********************* NEW USER CREATION COMPLETE *****************"
Write-Host ""
Write-Host -ForegroundColor Green "Displaying Active Directory Account Details"
Get-ADUser $ADAccountName

Write-Host -ForegroundColor Green "Displaying Microsoft Exchange Account Details"
Get-Mailbox -Identity $ADAccountName | ft DisplayName, PrimarySMTPAddress, Database, RetentionPolicy

Write-Host -ForegroundColor Green "Displaying Microsoft Lync Account Details"
Get-CsUser -Identity $ADAccountName | ft FirstName, LastName, WindowsEmailAddress, AudioVideoDisabled

# Remove Remote PowerShell Sessions
Remove-PSSession $LyncPowerShell
Remove-PSSession $ExchangePowerShell
Remove-PSSession $ADPowerShell

sleep -Seconds 10

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s