Enable users for Lync, via AD Group Membership

Hi.

I have written a small Powershell script that reads an Active Directory group, and Lync Enables users in that group or in any Groups-in-Groups.
The users e-mail address is used when enabling the user for Lync.

Changes will come to the script, in terms of more error checking and other improvments.

Requirements:

  • Needs access to Active Directory and Lync PowerShell modules

Please feel free to use the script AS-IS, and I’ll be happy for feedback, any kind 🙂

I have successfully created a scheduled task at several customers – They are all happy 🙂

Updates:

  • Changed the requirements of Log folder – Script creates logfile from where the command is called
  • Changed the format of Logfilename, Convertet to uFormat – Should cover most 🙂

Changes are based on feedback 🙂


#############################################################################################
# Enable-LyncUsers.ps1
#
# v1.0 - April 2012 by Trond Egil Gjelsvik-Bakke (https://trogjels.wordpress.com)
# v1.1 - October 2012
#        Changed script regarding to LogFile creation.
#
# Syntax:
#	Enable-LyncUsers AD-GroupName
#
#############################################################################################
param($CSGroup)

Import-Module ActiveDirectory
Import-Module Lync

#Check if AD Group contains members
$Members = Get-ADGroupMember $CSGroup -Recursive
if ($Members -eq $NULL)
{
    write-host "AD Group $CSGroup don't contain any users. Please add members to this group before continuing" -foregroundcolor red -backgroundcolor black
    exit 0
}

#Create LogFile
$LogFile = "Enable-LyncUsers-Log-"+(get-date -uformat %d%m%Y-%H%M%S)+".txt"
$LogTXT = "Processing Users.....`n"

Out-File -FilePath $LogFile -InputObject $LogTXT

Write-Host "Processing Users.....`n" -foregroundcolor Yellow -backgroundcolor Black

ForEach ($user in $Members)
{
	$samaccountname = $user.samaccountname

	$ADUser = get-csaduser -Filter {SamAccountName -eq $SamAccountName}

	$display = $ADUser.FirstName + " " + $ADUser.LastName

	write-host "Processing:" $display

	$adexist = get-csaduser | where {$_.samaccountname -eq $samaccountname}

	if ($adexist -eq $null)
    	{
        	$usernotinad = $true
		write-host "User " $samaccountname " not in AD"
    }

    else
    {
        $usernotinad = $false
    }

    if ($usernotinad -ne $true)
    {
        $enabled = Get-CsUser -filter {SamAccountName -eq $SamAccountName}

	# Check if user is enabled for for OCS/Lync
	if ($enabled)
	{
		# Check if user is enabled for OCS
	        if ($enabled.RegistrarPool -eq $null)
        	{
			Write-Host "User is on OCS, enabling for Lync" -foregroundcolor Yellow -backgroundcolor Black

			$pool = get-csservice -registrar | where {$_.ServiceID -eq "1-Registrar-1"}

			Move-CsLegacyUser -Identity $ADUser.SipAddress -Target $pool.PoolFQDN -Force -Confirm:$false
			$LogTXT = "Successfully moved $display to Lync Server 2010"

			Write-Host "Successfully moved $display to Lync Server 2010"
        	}

		else
		{
			Write-Host "User is already on Lync - Skipping..." -foregroundcolor Yellow -backgroundcolor Black
			$LogTXT = "$display is already on Lync Server 2010, skipping....."
		}
	}
	else
	{
		Write-Host "Enabling user for Lync - Processing..." -foregroundcolor Yellow -backgroundcolor Black

                $pool = get-csservice -registrar | where {$_.ServiceID -eq "1-Registrar-1"}

		get-csaduser | where {$_.samaccountname -eq $samaccountname} | Enable-Csuser -registrarpool $pool.PoolFQDN -sipaddresstype EmailAddress
		$LogTXT = "Successfully enabled $display for Lync Server 2010"

		Write-Host "Successfully enabled $display for Lync Server 2010" -foregroundcolor Yellow -backgroundcolor Black
	}
    }
	#Write Log
	Out-File -FilePath $LogFile -InputObject $LogTXT -Append
}

Advertisements

28 thoughts on “Enable users for Lync, via AD Group Membership

  1. $ADUser = get-csaduser | where {$_.samaccountname -eq $samaccountname}
    would be far more efficient (and faster) if you used
    $ADUser = get-csaduser -Filter {SamAccountName -eq $SamAccountName}

    the same with

    $enabled = get-csuser | where {$_.samaccountname -eq $samaccountname}
    would be more efficient as
    $enabled = Get-CsUser -filter {SamAccountName -eq $SamAccountName}

    as for
    if ($enabled -ne $null)
    you don’t need to see if it’s not null (essentially, if it’s true). you can use
    if ($enabled)
    that will pass if it’s true, and fail if it’s not.

    and you can programatically create the log folder by using Test-Path to see if it exists, and if not, doing a New-Item to create it.

  2. This is great – but I keep getting an error creating the logfile even though I created C:\LyncInstall\Scripts\Logs. The users still process I just don’t get any logs.

    $LogFile = “C:\LyncInstall\Scripts\Logs\Enable-LyncUserslog-“+(Get-Date -Format d).replace(“.”,””)+”-“+(Get-Date -Format t).replace(“:”,””)+”.txt”

    Out-File : Could not find a part of the path ‘C:\LyncInstall\Scripts\Logs\Enabl
    e-LyncUserslog-10\3\2012-1235 PM.txt’.
    At D:\Scripts\Enable-LyncUsers.ps1:26 char:9
    + Out-File <<<< -FilePath $LogFile -InputObject $LogTXT
    + CategoryInfo : OpenError: (:) [Out-File], DirectoryNotFoundExce
    ption
    + FullyQualifiedErrorId : FileOpenFailure,Microsoft.PowerShell.Commands.Ou
    tFileCommand

  3. This is great. I notice though if the user is in Lync and NOT enabled, that this script will not re-enable them.

    Also, what about a script to disable users from AD? I’ve been trying to find some method to cleanup Lync accounts by disabling them if they are removed from the group or moved to a disabled accounts OU. Thoughts on how to achieve this?

    good work!

  4. How can I utilize this script to change the default settings? I am using “Audio-Video Disabled” for telephony, and this script enables PC-to-PC Only in telephony. Thoughts?

  5. Actually, let me reword….can I utilize this script to enable Lync users with telephony set to Audio-Video-disabled instead of the default PC-to-PC Only setting?

  6. Hi.

    Yes, you can by utilizing the Set-CsUser
    Alter the script, and include Set-CsUser -AudioVideoDisabled $true

    It might be something like this:
    Write-Host “Enabling user for Lync – Processing…” -foregroundcolor Yellow -backgroundcolor Black

    $pool = get-csservice -registrar | where {$_.ServiceID -eq “1-Registrar-1”}

    get-csaduser | where {$_.samaccountname -eq $samaccountname} | Enable-Csuser -registrarpool $pool.PoolFQDN -sipaddresstype EmailAddress | Set-CsUser -AudioVideoDisabled $true
    $LogTXT = “Successfully enabled $display for Lync Server 2010”

    Write-Host “Successfully enabled $display for Lync Server 2010” -foregroundcolor Yellow -backgroundcolor Black

    Be sure to test the script after the change, to verify that expected result are accomplished.

  7. Pingback: Desember blog roll – Atea Lync Blog

  8. Thanks for this code it works great i only had to change the right Registrar pool id.
    We use different AD groups to grant lync rights (and thus the correct CAL’s)
    Per Ad group i have a seperate script that sets the right Policies accoording to this matrix:
    http://blogs.technet.com/b/csps/archive/2010/06/06/howtotelephony.aspx
    We use the $NULL because in other functions we have to set them to $true or $false
    {
    add-content -Encoding UTF8 -Path $LogFile -value (get-date) -passthru
    add-content -Encoding UTF8 -Path $LogFile -value ” – Enabled new user: $Display , Configure settings APP-Lync-Enterprise |`r`n” -passthru

    Write-Host “User beeing created…”
    Start-sleep -s 20

    Write-Host “set Telephony ‘Enterprise Voice'”
    get-csuser -Identity “$display” | Set-csUser -AudioVideoDisabled $False -EnterpriseVoiceEnabled $True -RemoteCallControlTelephonyEnabled $False
    Write-Host “Apply Client Conferencing Policy”
    get-csuser -Identity “$display” | Grant-CsConferencingPolicy -PolicyName “Tag:Lync-Enterprise”
    Write-Host “Apply Client Version Policy”
    get-csuser -Identity “$display” | Grant-CsClientVersionPolicy -PolicyName $NULL
    Write-Host “Apply External access Policy”
    get-csuser -Identity “$display” | Grant-CsExternalAccessPolicy -PolicyName “Tag:Remote Access + Federation”
    Write-Host “Apply Client Policy”
    get-csuser -Identity “$display” | Grant-CsClientPolicy -PolicyName $NULL
    Write-Host “Apply Voice Policy”
    get-csuser -Identity “$display” | Grant-CsVoicePolicy -PolicyName “Tag:Call-International”
    Write-Host “Apply DialPlan Policy”
    get-csuser -Identity “$display” | Grant-CsDialPlan -PolicyName “Tag:Company-department”
    Write-Host “Successfully enabled $display for Lync Server 2010” -foregroundcolor Yellow -backgroundcolor Blue
    }
    ###
    And if you add these lines at the bottem it wil send you an e-mail:

    # And now Send logfile to The Lync Engineer
    # give 2 second wait for the logfile to finish up
    Start-sleep -s 2
    $messageBody = Get-Content -Encoding UTF8 -Path ($LogFile);
    $smtpClient = New-Object System.Net.Mail.SmtpClient;
    $smtpClient.Host = ‘mail.abc.press’;
    $smtpClient.Port = 25;
    #remember to add this server to the mailserver
    $smtpClient.Send(‘myservername@stage.press’,’helpdesk@stage.press’,$LogFile, $messageBody);
    #

  9. Does this work for Lync 2013 ? I know its a newb question but to kick if off I am running ./Enable-Lyncuser.ps1 Groupname. It never seems to take my group name. Also, how does it know what pool I want the users put into.

  10. I find it takes about 15 seconds per users. I have about 6000 users. Any tips on how to make it run faster ? Thanks.

  11. Hi..
    To make it run faster, you could remove some checking for OCS and things..

    This might speed things up a bit, especially if this is a clean Lync install with no OCS installation previous.

    See if that helps..

  12. Hello,

    I am attempting to import my AD users into Lync 2013. Just wanted to confirm, does this script also work for 2013?

    Also, is your scheduled task running this on the Lync Front End server or another location?

    Thank you!

  13. Could you please share the running procedure also for the script ? Does it need to run from FE or it can run from AD also ?

  14. Hi everyone,

    When i run this script I’m getting an error when it try to enable a member or member in the group. The error message is the next one:

    Enable-Csuser : Email address is not valid. Specify a valid email address and
    then try again.
    At line:42 char:72
    + get-csaduser | where {$_.samaccountname -eq $samaccountname} |
    Enable-Cs …
    +
    ~~~~~~~~
    +CategoryInfo : InvalidOperation: (CN=OLIVARES\, J…=MXTAD,DC=corp:OCSADUserAll) [Enable-CsUser], ManagementException
    +FullyQualifiedErrorId : EnableCSUser,Microsoft.Rtc.Management.AD.Cmdlets.EnableOcsUserCmdlet

    For your information, I made an AD group and a member of that group is the User Jorge Olivares with OLIVARESJ as his username. If I add a user in lync server i just search a user -> I assign the user to a pool and then I choose the format @mxtad.corp and after that I just clic on enable.

    That’s enough to let a user use his lync client just changing his sign-in address in options with the format specified for example: olivaresj@mxtad.corp
    When that is made just is necessary to clic on ok an then signin.

    Something is wrong whit the email parameter, but i don´t know what parameter use or what I need to change in the script to fix this problem. Can you help me with this problem please my friends?

    Best Regards.

  15. I realize this is an old post but the script works great and I was wondering if it is possible to remove users from Lync based on them not being in the AD-GroupName. So, ultimately, the only users we want using Lync are those who are in the AD group. Thx

  16. Here is the modified script we came up with to control both enable and disable based on AD group membership. I just run this in a scheduled task that outputs to a text file and overwrites every time it runs.

    # Assign ALL USERS to a dynamic array
    $allUsers = Get-CsAdUser -ResultSize:unlimited

    # Assign all members of the ALLOWED GROUP to a dynamic array
    $groupUsers = Get-ADGroupMember -Identity “” -Recursive

    # Loop through array of all users
    foreach ($member in $allUsers)
    {
    $str = “”

    # Determine if current user is member of allowed group
    if(($groupUsers | where-object{$_.samaccountname -eq $member.samaccountname}))
    {
    # If user already has Lync enabled, do nothing
    if ((Get-CsUser | where {$member.SamAccountName -eq $_.SamAccountName}) -ne $NULL )
    {
    $str += “Lync already enabled – ”
    }
    # If user does not have Lync enabled, enable it
    else
    {
    $member | Enable-Csuser -registrarpool -sipaddresstype EmailAddress
    $str += “Enabling Lync – ”
    }
    }

    # If user is not member of allowed group, disable Lync
    else
    {
    if ((Get-CsUser | where {$member.SamAccountName -eq $_.SamAccountName}) -ne $NULL )
    {
    $member | Disable-Csuser
    $str = “Disabling Lync – ”
    }
    else
    {
    $str += “Lync already disabled – ”
    }
    }

    $str += $member.Name + “`n”
    echo $str
    }

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