Skip to content

Powershell script to import LDAP object into exchange contact

Whith this powershell script, it’s possible to import external ldap object into active directory mail-contact.

Exchange will parse and create a list of contact available for everyone.

The script will clear all OU before importing.

$ErrorActionPreference = 'Stop'
#load Exchange pssnapin
Add-PSSnapIn Microsoft.Exchange.Management.PowerShell.SnapIn
#load Assembly DirectoryServices
[System.Reflection.Assembly]::LoadWithPartialName("System.DirectoryServices.Protocols") 
[System.Reflection.Assembly]::LoadWithPartialName("System.Net") 
$body = ""
start-transcript
get-date
#---------------------------------------------
$OUS="TEST","TEST2","TEST3"
foreach ($OU in $OUS)
{
	#----------------------------------------------------------------------------------------------------------
	#load user and password to logon in Openldap
	$count = 0
	$UserName = "uid=reader,ou=users,dc=test,dc=eu"  
	$Password = "CgtCat34"
	$BODY= $body + "`n Processing OU "+$OU+"`n"
	$filter = "(objectclass=inetOrgPerson)"
	#Insert openLDAP source server and the OU of the company created in this openLDAP 
	$domain = "LDAP://10.241.37.1:389/o="+$OU+",dc=test,dc=eu"

	#Launch the search in the openLDAP
	$root = New-Object -TypeName System.DirectoryServices.DirectoryEntry($domain,$UserName,$Password,'FastBind')
	$query = New-Object System.DirectoryServices.DirectorySearcher($root,$filter)
	$objuser = $query.findall()
	#write-host "NO ERROR"
	#exit(1)
	get-mailcontact -ResultSize Unlimited -OrganizationalUnit ("OU="+$OU+",OU=LDAP-XXX,DC=TEST,DC=local") -filter {CustomAttribute11 -ne $null}|set-mailcontact -CustomAttribute11 ""
	Start-Sleep -s 30 #delay of 30 seconds to let AD to replicate the contact in the DCS servers

	#search user by user in the openLDAP ou
	foreach ($user in $objUser.GetEnumerator()) {
	  
		#this counter is only a security counter and for testing porpouses, in case of you dont want to launch all users at the same time
		if ($count -ge 0) #insert the number of users you want to import
		{ 
			write-host "-------------------------------------------------------"
			#select the mail of the user in openLDAP
			if ($user.properties.mail -eq $null)
			{ 
				$smtpmail=""
				write-host "the contact has empty email address" $user.properties.displayname
			}
			else
			{
				$smtpmail=""
				$smtpmail = [Microsoft.Exchange.Data.ProxyAddress]("$($user.properties.mail)")		
			}

		if(-not([string]::IsNullOrEmpty($smtpmail.SmtpAddress))) # check if the smtp field is not empty
		{
		
		$mail = $smtpmail.SmtpAddress        
		write-host $user.properties.cn
	   
		If ([string]$user.properties.displayname -ne (Get-MailContact ([string]$user.properties.displayname) -ErrorAction silentlycontinue)) #check if the user exist in the AD yet   
		{
			If ( (get-mailcontact -ResultSize Unlimited  -OrganizationalUnit ("OU="+$OU+",OU=LDAP-XXX,DC=TEST,DC=local") -filter {WindowsEmailAddress -eq $mail}) -eq $null ) 
			{
				write-host "the contact doesnt exist, I create it"
				#change the OU where the contacts will be created in your AD, changing "-organizationalunit" property
				New-MailContact -Name $user.properties.cn -DisplayName $user.properties.displayname -FirstName $user.properties.givenname -LastName $user.properties.sn -OrganizationalUnit ("OU="+$OU+",OU=LDAP-XXX,DC=TEST,DC=local") -ExternalEmailAddress $mail #-Alias $_.mailNickname
				Start-Sleep -s 30 #delay of 15 seconds to let AD to replicate the contact in the DCS servers		
				Write-host "update contacts properties.... " $user.properties.displayname
				Set-Contact -identity ([string]$user.properties.displayname) -Phone $user.properties.telephonenumber -mobilePhone $user.properties.mobile -Office $user.properties.physicaldeliveryofficename -Title $user.properties.title -Department $user.properties.department -Company $user.properties.o -city $user.properties.l
				set-Mailcontact -identity ([string]$user.properties.displayname) -CustomAttribute10 $OU
				Set-Mailcontact -identity ([string]$user.properties.displayname) -CustomAttribute11 "updated"
				$BODY=$BODY+"ADDED "+$user.properties.displayname+"`n"
			}
			else
			{
				write-host "contact has been renamed"
			}
		}
		Else
		{
			write-host "the contact exist"
			Write-host "update contacts properties.... " $user.properties.displayname
			Set-Contact -identity ([string]$user.properties.displayname) -Phone $user.properties.telephonenumber -mobilePhone $user.properties.mobile -Office $user.properties.physicaldeliveryofficename -Title $user.properties.title -Department $user.properties.department -Company $user.properties.o -city $user.properties.l
			Set-Mailcontact -identity ([string]$user.properties.displayname) -CustomAttribute10 $OU -ForceUpgrade
			Set-Mailcontact -identity ([string]$user.properties.displayname) -CustomAttribute11 "updated" -ForceUpgrade
			#$BODY=$BODY+"UPDATED "+$user.properties.displayname+"`n"
		}
		
		
		}
		$count++
		}
	}
	#Remove all contact not updated
	Start-Sleep -s 60 #delay of 60 seconds to let AD to replicate the contact in the DCS servers
	Write-host "start removing removed contact.... "
	$removed=get-mailcontact -ResultSize Unlimited  -OrganizationalUnit ("OU="+$OU+",OU=LDAP-XXX,DC=TEST,DC=local") -filter {CustomAttribute11 -eq $null}|% { $_.Name}
	if ($removed) {
		$body = $body + "REMOVED " + ($removed -join "`nREMOVED ")
		$body = $body + "`n------------------------------------------------------`n"
	}
	get-mailcontact -OrganizationalUnit ("OU="+$OU+",OU=LDAP-XXX,DC=TEST,DC=local") -filter {CustomAttribute11 -eq $null}|remove-mailcontact -Confirm:$false
}
#----------------------------------------------------------------------------------------------------------
get-date
stop-transcript
$log = Get-childitem -Filter *.txt c:\users\administrator\Documents | sort LastWriteTime | select -last 1
send-mailmessage -from "Administrator <[email protected]>" -to "Test <[email protected]>" -subject "LDAP Import" -attachment C:\users\administrator\Documents\$log -body $BODY -smtpServer smtp.isp.it
#----------------------------------------------------------------------------------------------------------
$Daysback = "-7"
 
$CurrentDate = Get-Date
$DatetoDelete = $CurrentDate.AddDays($Daysback)
Get-ChildItem -Filter *.txt c:\users\administrator\Documents | Where-Object { $_.LastWriteTime -lt $DatetoDelete } | Remove-Item