New User Exchange & Lync Settings

Doctor Scripto

Summary: Guest blogger Tim Bolton discusses a script to create new Exchange uses and Lync settings.

 Microsoft Scripting Guy, Ed Wilson, is here. Today we have a special treat – a cool Windows PowerShell script to create new Exchange users and the associated Lync settings. Tim has written a very popular guest blog article earlier this year in which he talked about a real-world example that led him to learning Windows PowerShell. You can read his previous article, and see his biography here: Why should I learn PowerShell? Real world example saves the day!

Take it away, Tim.

Following the rule of POSH, if you have to do something more than twice, script it …

In my current position, one of the common daily tasks is to place a new user into Exchange and Lync. This is not hard to do via the GUI but it is so redundant, which is why with the help and inspiration of my co-worker Brian Peacock, this script came to life.

Thank you, Claus Thude Nielsen, for showing me the Here-String method that cleaned up my email notices.

Also, thank you goes out to Josh Falls and Chris Duck for their patience and support.

I will answer some of the most common questions I have received about this script.

  1. Yes, Josh, I know I’m killing puppies with the Write-Host, BUT it’s just for visual verification and to appease the people running it that YES something is happening so please quit hitting enter…
  2. Why the $VerifyRequester and $VerifyNewUserID? This is for error handling; I want it to die if someone puts in the wrong info.  Better to start over then to try to fix an account that is now setup
    incomplete and wrong.
  3. Why are the functions at the top? I never created a function or used one in a script before, so there you go…  : )
  4. Why the -Sleep instead of verifying a setting on Lync or Exchange?  Chris, I am actually waiting on Lync to update itself, which takes the same amount of time that I set each time. I could use POSH  to look for a setting and it will be there, just not throughout the entire system, so it’s easier to use the KISS principal and be sure.
  5. Why are you sending a BCC to yourself? To ensure that it went out correctly, and then I copy and paste the email into the ticket notes so I can close it.

Here is an example. Four entries, verify my settings, hit YES, and then check in a couple minutes after grabbing a cup of coffee.

 

 

So here we go..!

Note  The complete script is uploaded to the Scripting Guys Script Repository.

 

 <#

      .SYNOPSIS

      Set up a new users Exchange and Lync settings.   

      .DESCRIPTION

This will be used to set up a new user’s Exchange and Lync settings for our companies A, B, & C.  We will add other companies in the future, if we deem it necessary.

      .EXAMPLE

      .\newuser.ps1  

      .NOTES

If there is any error the script will stop. The error message will be sent to a text file on your local C: Drive i.e. C:\Error.txt. You MUST run these two functions bsp-exc & bsp-Lync that are in your Windows PowerShell profile PRIOR to running this script or it will fail.

#Load Lync

function bsp-lync

{

write-host -ForegroundColor green -BackgroundColor black “Loading Lync Server 2010 RM”

$newlyncsession = New-PSSession -ConnectionUri https://lyncweb.BigDog.com/ocspowershell -credential “BigDog\TimBolton”

import-pssession -session $newlyncsession

}

 

#Load Exchange

function bsp-exc

{

write-host -ForegroundColor green -BackgroundColor black “Loading Exchange Server 2010 RM”

$newexcsession = New-PSSession -ConfigurationName Microsoft.Exchange -ConnectionUri http://Exchange01.BigDog.ad/PowerShell/ -Authentication Kerberos -Credential “BigDog\TimBolton”

import-pssession -session $newexcsession

}

#>

 

# This will be used as a Yes or No option after you are satisfied with the variable settings.

Function Verify-Variables {

      “`r`n” 

      $message = “Do you want to continue?”

      $yes = New-Object System.Management.Automation.Host.ChoiceDescription “&Yes”, `

    “Compiling Script.”

      $no = New-Object System.Management.Automation.Host.ChoiceDescription “&No”, `

    “Exiting Script.”

      $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

      $result = $host.ui.PromptForChoice($title, $message, $options, 0)

switch ($result)

    {

        0 {

            “`r`n” 

            Write-Host -foregroundcolor Green “You selected Yes.”      

            “`r`n” 

            }

            1 {

            “`r`n” 

            Write-Host -foregroundcolor Red “You selected No. Exiting Script.”

            “`r`n” 

            exit

            }

      }

}

 

# This will be used as a Yes or No option to send out the Email Notices.

Function Email-Notices {

      “`r`n” 

      $message = “Do you want to send out the Email Notices?”

      $yes = New-Object System.Management.Automation.Host.ChoiceDescription “&Yes”, `

            “Sending Email Notices.”    

      $no = New-Object System.Management.Automation.Host.ChoiceDescription “&No”, `

            “Exiting Script.”

      $options = [System.Management.Automation.Host.ChoiceDescription[]]($yes, $no)

      $result = $host.ui.PromptForChoice($title, $message, $options, 0)

switch ($result)

    {

        0 {

            “`r`n” 

            Write-Host -foregroundcolor Green “You selected Yes. Sending Email Notices.”        

            “`r`n” 

            }

            1 {

            “`r`n” 

            Write-Host -foregroundcolor Red “You selected No. Exiting Script.”

            “`r`n” 

            exit

            }

}

}

 

# Error Action Preference is set to Stop since I want it to quit before any setting are set incorrectly.

$ErrorActionPreference = ‘Stop’

Trap {

      $_ | Out-File C:\Error.txt -append

      Write-Host -ForegroundColor Red “There was a fatal error check C:\Error.txt”

      Exit

      }

 

# User Specific – Incedent Number – Who Requested the New User Request – New UserID.

$IncedentNumber=Read-Host “What is the Incident Number? “

$Requester=Read-Host “What is the UserID for the Requester ? “

$VerifyRequester = Get-ADUser $Requester

$NewUserID=Read-Host “What is the UserID for the New User ? “

$VerifyNewUserID=Get-ADUser $NewUserID

 

# The New Phone Number & Extension & First Six of number for the User.

Do {

      $Phone=Read-Host “What is the New 10 digit Phone Number with dashs? “

      } while ($Phone -match “^\d\d\d\-\d\d\d\-\d\d\d\d$” -ne “True” )

      $Extension=$Phone.substring($phone.length-4)

      $FirstSix = $Phone.Substring(0,7) 

   

# Get all AD properties of New User.

$NewUser=(Get-ADUser $NewUserID -Properties *)

$NewUserEmailaddress=$NewUser.mail

$ManagerID=$NewUser.Manager

$NewUserName=$NewUser.DisplayName

$NewUserFirstName=$NewUser.GivenName

 

# Line URI and SIP Address for New User.

$LineURI= “tel:+1” + $Phone.Replace(“-“, “”)

$SIPAddress = “sip:” + $NewUserEmailaddress

 

# Get Manager & Requester & MY Email Address for Email Notification.

$ManagerEmail=(Get-ADUser $ManagerID -Properties mail).mail

$RequesterEmail=(Get-ADUser $Requester -Properties mail).Mail

$RequesterFirstName=(Get-ADUser $Requester -Properties GivenName).GivenName

$MyName = $env:username

$MyEmail = (Get-ADUSer $MyName -Properties mail).mail

 

# Switch – User’s Registrar Pool & Voice Policy & Dial Plan Settings will be chosen by the first 6 digits of the user’s phone number.

Switch -Regex ($FirstSix) {

    “212-555|978-333|978-666|978-777” {

    # Company A Settings

    $lyncserver=”CompanyA-lyncpool.BigDog.ad”

    $voicepolicy=”CompanyA-National”

    $dialplan=”CompanyA”

    break}

    “944-555|945-911” {

    # Company B & C  Settings

    $lyncserver=”CompanyBC-lyncpool.BigDog.ad”

    $voicepolicy=”CompanyBC-National”

    $dialplan=”CompanyBC”

    break}

}

$conferencingpolicy=”<=25 part., no ip Video”

$externalaccesspolicy=”Allow Outside Access”

$UMMailboxPolicy=”CompanyA-DP Default Policy”

$EUMAdd=”eum:$Extension;phone-context=DirectFromAudiocodes-Temp.BigDog.ad”

 

# Visually verify Variables prior to any settings being made.

“`r`n” 

write-host -foregroundcolor Green ” —— Verify The Variables —— “

“`r`n” 

write-host -foregroundcolor Red “Username; $NewUserID”

write-host -foregroundcolor Red “SIP Address; $SIPAddress”

write-host -foregroundcolor Red “Registar Pool; $lyncserver”

write-host -foregroundcolor Red “Phone Number; $Phone”

write-host -foregroundcolor Red “Extension; $Extension”

write-host -foregroundcolor Red “Line URI; $LineURI”

 

# Calling the Verify Variable Yes or No function.

Verify-Variables

 

# Configure AD phone and enable for Lync.

write-host -foregroundcolor Yellow “Setting User Phone Number”

set-user -Identity $NewUserID -Phone $phone

 

# Pause 10 for Lync changes.

write-host -foregroundcolor Green “Checking for replication”

Start-Sleep -s 10

 

# Enable CSUser.

write-host -foregroundcolor Yellow “Enabling Lync for $username with $sipaddress on $lyncserver”

Enable-csuser -Identity $NewUserID -registrarpool $lyncserver -sipaddress $sipaddress

 

# Pause 10 for Lync changes.

write-host -foregroundcolor Green “Waiting for Lync Changes to propogate”

Start-Sleep -s 45

 

# Display Lync settings for user.

Write-Host -foregroundcolor Yellow “Configuring Lync Policies”

Set-CSUser -Identity $NewUserID -enterprisevoiceenabled $True -lineuri $lineuri

Grant-CSVoicePolicy -Identity $NewUserID -policyname $voicepolicy

Grant-CSDialPlan -Identity $NewUserID -policyname $dialplan

Grant-CsConferencingPolicy -Identity $NewUserID -PolicyName $conferencingpolicy

Grant-CSExternalAccessPolicy -Identity $NewUserID -policyname $externalaccesspolicy

 

# Pause 30 for Lync changes.

write-host -foregroundcolor Green “Pausing 30 Seconds for Lync Changes”

Start-Sleep -s 30

 

# Enable Unified Messaging.

write-host -foregroundcolor Yellow “Enabling UM”

Enable-UMMailbox -Identity $NewUserID -UMMailboxPolicy $UMMailboxPolicy -Extensions $Extension -PinExpired:$false

Set-Mailbox -Identity $NewUserID -EmailAddresses @{add=$EUMAdd}

 

# Set the UMMailbox For Operator Number if needed. Some have this, some do not. Again Settings will be chosen by the first 6 digits of the user’s phone number.

Switch -Regex ($FirstSix) {

 “944-555” {

# Company B – Set-UMMailbox

 Set-UMMailbox -Identity $NewUserID -OperatorNumber “6600”

 break}

}

     

# Pause 30 seconds and provide summary.

write-host -foregroundcolor Green “Pausing 30 seconds for changes, then will provide a summary, if you do not wish to view the summary here you may close this window.”

Start-Sleep -s 30

write-host -foregroundcolor Green “Mailbox Summary”

Get-Mailbox $NewUserID

write-host -foregroundcolor Green “Press any key to view UM and Lync Summaries …”

$x = $host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”)

get-ummailbox $NewUserID

write-host -foregroundcolor Green “Press any key to view Lync Summary…”

$x = $host.UI.RawUI.ReadKey(“NoEcho,IncludeKeyDown”)

Get-CSUser $NewUserID

 

# Calling the Email Notices Yes or No function.

Email-Notices

 

# Send Email Notification to the Requester, Manager, Messaging Team Member setting up the account so that New User account setup has been completed.

$PSEmailServer = “mailman.BigDog.com”

$Subject = “New User Request for :” + $NewUserName + ”  – Incident Number : #” + $IncedentNumber

$body1 = @”

Hello $RequesterFirstName

The New User Exchange\Lync Account for : $NewUserName has been completed.

UserID : $NewUserID

Email Address : $NewUserEmailaddress

They have been assigned the phone number : $Phone

They have been assigned the voice mail extension : $Extension

—————————————————————————–

Please wait over night for the new account to take effect.

If you have any questions, please contact the Service Desk at 888-888-8888 or Ext: 1001

Services Desk Email: servicedesk@BigDog.com

PLEASE DO NOT REPLY TO THIS EMAIL. REPLIES TO THIS ADDRESS ARE ROUTED TO AN UNMONITORED MAILBOX.

—————————————————————————–

“@

$Email1 = @{

From = “UnifiedMessaging@BigDog.com”

To = “$RequesterEmail”

Cc = “$ManagerEmail”

Bcc = “$MyEmail”

Subject = “$Subject”

Body = “$Body1”

}

Send-MailMessage @email1

$body2 = @”

Hello $NewUserFirstName.   Welcome to Company Name.

Your New UserID is : $NewUserID

Your New Email Address is : $NewUserEmailaddress

You have been assigned the phone number : $Phone

You have been assigned the voice mail extension : $Extension

—————————————————————————–

Please wait over night for the new account to take effect.

If you have any questions, please contact the Service Desk at 888-888-8888 or Ext: 1001

Services Desk Email: servicedesk@BigDog.com

PLEASE DO NOT REPLY TO THIS EMAIL. REPLIES TO THIS ADDRESS ARE ROUTED TO AN UNMONITORED MAILBOX.

—————————————————————————–

“@

$Email2 = @{

From = “UnifiedMessaging@BigDog.com”

To = “$NewUserEmailaddress”

Cc = “$ManagerEmail”

Bcc = “$MyEmail”

Subject = “$Subject”

Body = “$Body2”

}

Send-MailMessage @email2

Exit

Thank you, Tim, for an excellent article. Join me tomorrow for more cool Windows PowerShell stuff.

I invite you to follow me on Twitter and Facebook. If you have any questions, send email to me at scripter@microsoft.com, or post your questions on the Official Scripting Guys Forum. See you tomorrow. Until then, peace.

Ed Wilson, Microsoft Scripting Guy

0 comments

Discussion is closed.

Feedback usabilla icon