Script to import GAL into Contact Folder

Hi,

I'm using this script to copy GAL contacts to a contact folder in some mailbox users.

https://gallery.technet.microsoft.com/scriptcenter/Importing-Global-Address-dc52a0ce

This script, search for a folder in contacts folder of user mailbox. If found, empty it, if not found, creates it. Once done whatever, begins to create contacts from GAL into the folder.

But I need not to empty the folder if exists, but check if the contact taken from the GAL exists in the folder. if not, create it; if exists, overwrite Name and Surname, telephone number and email address, leaving all other data without change.

I am not a Powershell EWS expert, and I don't know how to afford this. I have been searching a way to find and modify contacts, with no luck.

Could somebody help me?

Thanks

June 18th, 2015 11:38am

Here's a script that will create a contact in a contact folders if it doesn't exist you should be able to fill the rest of the logic in you need in around that

####################### 
<# 
.SYNOPSIS 
 Create an Contact from Commandline using Powershell and the Exchange Web Services API in a Mailbox in Exchange if a contact with the EmailAddress passed in Cant be resolved 
 
.DESCRIPTION 
  Create an Contact from Commandline using Powershell and the Exchange Web Services API in a Mailbox in Exchange if a contact with the EmailAddress passed in Cant be resolved 
 
 Requires the EWS Managed API from https://www.microsoft.com/en-us/download/details.aspx?id=42951

.EXAMPLE
 PS C:\>Create-Contact  -MailboxName user.name@domain.com -DisplayName DisplayName -FirstName John -LastName Doe -Credential (Get-Credential) -EmailAddress johndoe@domain.com -Company Company -Department Department -Office Office -BusinessPhone BusinessPhone -MobilePhone MobilePhone
 This Example creates an Contact in a Mailboxes Contact folder if a Contact with the EmailAddress passed in Cant be resolved 
#> 
function Create-Contact 
{ 
    [CmdletBinding()] 
    param( 
    	[Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
 		[Parameter(Position=1, Mandatory=$true)] [string]$DisplayName,
		[Parameter(Position=2, Mandatory=$true)] [string]$FirstName,
		[Parameter(Position=3, Mandatory=$true)] [string]$LastName,
		[Parameter(Position=4, Mandatory=$true)] [string]$EmailAddress,
		[Parameter(Position=5, Mandatory=$false)] [string]$Company,
		[Parameter(Position=6, Mandatory=$true)] [PSCredential]$Credentials,
		[Parameter(Position=7, Mandatory=$false)] [string]$Department,
		[Parameter(Position=8, Mandatory=$false)] [string]$Office,
		[Parameter(Position=9, Mandatory=$false)] [string]$BusinssPhone,
		[Parameter(Position=10, Mandatory=$false)] [string]$MobilePhone,
		[Parameter(Position=10, Mandatory=$false)] [string]$JobTitle,
		[Parameter(Position=11, Mandatory=$false)] [string]$Notes
    )  
 	Begin
		 {
		## Load Managed API dll  
		###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
		$EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")
		if (Test-Path $EWSDLL)
		    {
		    Import-Module $EWSDLL
		    }
		else
		    {
		    "$(get-date -format yyyyMMddHHmmss):"
		    "This script requires the EWS Managed API 1.2 or later."
		    "Please download and install the current version of the EWS Managed API from"
		    "http://go.microsoft.com/fwlink/?LinkId=255472"
		    ""
		    "Exiting Script."
		    exit
		    } 
  
		## Set Exchange Version  
		$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2  
		  
		## Create Exchange Service Object  
		$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)  
		  
		## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials  
		  
		#Credentials Option 1 using UPN for the windows Account  
		#$psCred = Get-Credential  
		$creds = New-Object System.Net.NetworkCredential($Credentials.UserName.ToString(),$Credentials.GetNetworkCredential().password.ToString())  
		$service.Credentials = $creds      
		#Credentials Option 2  
		#service.UseDefaultCredentials = $true  
		 #$service.TraceEnabled = $true
		## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
		  
		## Code From http://poshcode.org/624
		## Create a compilation environment
		$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
		$Compiler=$Provider.CreateCompiler()
		$Params=New-Object System.CodeDom.Compiler.CompilerParameters
		$Params.GenerateExecutable=$False
		$Params.GenerateInMemory=$True
		$Params.IncludeDebugInformation=$False
		$Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
		$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
		$TAAssembly=$TAResults.CompiledAssembly

		## We now create an instance of the TrustAll and attach it to the ServicePointManager
		$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
		[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

		## end code from http://poshcode.org/624
		  
		## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use  
		  
		#CAS URL Option 1 Autodiscover  
		$service.AutodiscoverUrl($MailboxName,{$true})  
		"Using CAS Server : " + $Service.url   
		   
		#CAS URL Option 2 Hardcoded  
		  
		#$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
		#$service.Url = $uri    
		  
		## Optional section for Exchange Impersonation  
		  
		#$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 

		# Bind to the Contacts Folder
		$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Contacts,$MailboxName)   
		$Contacts = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
	    $type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
		$type = $type.MakeGenericType("Microsoft.Exchange.WebServices.Data.FolderId" -as "Type")
		$ParentFolderIds = [Activator]::CreateInstance($type)
		$ParentFolderIds.Add($Contacts.Id)
		$Error.Clear();
		$ncCol = $service.ResolveName($EmailAddress,$ParentFolderIds,[Microsoft.Exchange.WebServices.Data.ResolveNameSearchLocation]::ContactsOnly,$true);
		if($Error.Count -eq 0){
	        if ($ncCol.Count -eq 0)  
	        {  
				$Contact = New-Object Microsoft.Exchange.WebServices.Data.Contact -ArgumentList $service 
				#Set the GivenName
				$Contact.GivenName = $FirstName
				#Set the LastName
				$Contact.Surname = $LastName
				#Set Subject  
				$Contact.Subject = $DisplayName
				$Contact.FileAs = $DisplayName
				$Contact.CompanyName = $Company
				$Contact.DisplayName = $DisplayName
				$Contact.Department = $Department
				$Contact.OfficeLocation = $Office
				$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone] = $BusinssPhone
				$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::MobilePhone] = $MobilePhone
				#Set the Location  
				$Contact.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1] = $EmailAddress
				#Set any Notes  
				$Contact.Body = $Notes
				$Contact.JobTitle = $JobTitle
		   		$Contact.Save($Contacts.Id)  
				Write-Host ("Contact Created")
			}
			else
			{		
				Write-Host ("Contact Already exists")
			}
		}
	}
}
Cheers
Glen
Free Windows Admin Tool Kit Click here and download it now
June 19th, 2015 11:09am

Here's a script that will create a contact in a contact folders if it doesn't exist you should be able to fill the rest of the logic in you need in around that

####################### 
<# 
.SYNOPSIS 
 Create an Contact from Commandline using Powershell and the Exchange Web Services API in a Mailbox in Exchange if a contact with the EmailAddress passed in Cant be resolved 
 
.DESCRIPTION 
  Create an Contact from Commandline using Powershell and the Exchange Web Services API in a Mailbox in Exchange if a contact with the EmailAddress passed in Cant be resolved 
 
 Requires the EWS Managed API from https://www.microsoft.com/en-us/download/details.aspx?id=42951

.EXAMPLE
 PS C:\>Create-Contact  -MailboxName user.name@domain.com -DisplayName DisplayName -FirstName John -LastName Doe -Credential (Get-Credential) -EmailAddress johndoe@domain.com -Company Company -Department Department -Office Office -BusinessPhone BusinessPhone -MobilePhone MobilePhone
 This Example creates an Contact in a Mailboxes Contact folder if a Contact with the EmailAddress passed in Cant be resolved 
#> 
function Create-Contact 
{ 
    [CmdletBinding()] 
    param( 
    	[Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
 		[Parameter(Position=1, Mandatory=$true)] [string]$DisplayName,
		[Parameter(Position=2, Mandatory=$true)] [string]$FirstName,
		[Parameter(Position=3, Mandatory=$true)] [string]$LastName,
		[Parameter(Position=4, Mandatory=$true)] [string]$EmailAddress,
		[Parameter(Position=5, Mandatory=$false)] [string]$Company,
		[Parameter(Position=6, Mandatory=$true)] [PSCredential]$Credentials,
		[Parameter(Position=7, Mandatory=$false)] [string]$Department,
		[Parameter(Position=8, Mandatory=$false)] [string]$Office,
		[Parameter(Position=9, Mandatory=$false)] [string]$BusinssPhone,
		[Parameter(Position=10, Mandatory=$false)] [string]$MobilePhone,
		[Parameter(Position=10, Mandatory=$false)] [string]$JobTitle,
		[Parameter(Position=11, Mandatory=$false)] [string]$Notes
    )  
 	Begin
		 {
		## Load Managed API dll  
		###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
		$EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")
		if (Test-Path $EWSDLL)
		    {
		    Import-Module $EWSDLL
		    }
		else
		    {
		    "$(get-date -format yyyyMMddHHmmss):"
		    "This script requires the EWS Managed API 1.2 or later."
		    "Please download and install the current version of the EWS Managed API from"
		    "http://go.microsoft.com/fwlink/?LinkId=255472"
		    ""
		    "Exiting Script."
		    exit
		    } 
  
		## Set Exchange Version  
		$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2  
		  
		## Create Exchange Service Object  
		$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)  
		  
		## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials  
		  
		#Credentials Option 1 using UPN for the windows Account  
		#$psCred = Get-Credential  
		$creds = New-Object System.Net.NetworkCredential($Credentials.UserName.ToString(),$Credentials.GetNetworkCredential().password.ToString())  
		$service.Credentials = $creds      
		#Credentials Option 2  
		#service.UseDefaultCredentials = $true  
		 #$service.TraceEnabled = $true
		## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
		  
		## Code From http://poshcode.org/624
		## Create a compilation environment
		$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
		$Compiler=$Provider.CreateCompiler()
		$Params=New-Object System.CodeDom.Compiler.CompilerParameters
		$Params.GenerateExecutable=$False
		$Params.GenerateInMemory=$True
		$Params.IncludeDebugInformation=$False
		$Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
		$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
		$TAAssembly=$TAResults.CompiledAssembly

		## We now create an instance of the TrustAll and attach it to the ServicePointManager
		$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
		[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

		## end code from http://poshcode.org/624
		  
		## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use  
		  
		#CAS URL Option 1 Autodiscover  
		$service.AutodiscoverUrl($MailboxName,{$true})  
		"Using CAS Server : " + $Service.url   
		   
		#CAS URL Option 2 Hardcoded  
		  
		#$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
		#$service.Url = $uri    
		  
		## Optional section for Exchange Impersonation  
		  
		#$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 

		# Bind to the Contacts Folder
		$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Contacts,$MailboxName)   
		$Contacts = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
	    $type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
		$type = $type.MakeGenericType("Microsoft.Exchange.WebServices.Data.FolderId" -as "Type")
		$ParentFolderIds = [Activator]::CreateInstance($type)
		$ParentFolderIds.Add($Contacts.Id)
		$Error.Clear();
		$ncCol = $service.ResolveName($EmailAddress,$ParentFolderIds,[Microsoft.Exchange.WebServices.Data.ResolveNameSearchLocation]::ContactsOnly,$true);
		if($Error.Count -eq 0){
	        if ($ncCol.Count -eq 0)  
	        {  
				$Contact = New-Object Microsoft.Exchange.WebServices.Data.Contact -ArgumentList $service 
				#Set the GivenName
				$Contact.GivenName = $FirstName
				#Set the LastName
				$Contact.Surname = $LastName
				#Set Subject  
				$Contact.Subject = $DisplayName
				$Contact.FileAs = $DisplayName
				$Contact.CompanyName = $Company
				$Contact.DisplayName = $DisplayName
				$Contact.Department = $Department
				$Contact.OfficeLocation = $Office
				$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone] = $BusinssPhone
				$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::MobilePhone] = $MobilePhone
				#Set the Location  
				$Contact.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1] = $EmailAddress
				#Set any Notes  
				$Contact.Body = $Notes
				$Contact.JobTitle = $JobTitle
		   		$Contact.Save($Contacts.Id)  
				Write-Host ("Contact Created")
			}
			else
			{		
				Write-Host ("Contact Already exists")
			}
		}
	}
}
Cheers
Glen
June 19th, 2015 11:09am

Here's a script that will create a contact in a contact folders if it doesn't exist you should be able to fill the rest of the logic in you need in around that

####################### 
<# 
.SYNOPSIS 
 Create an Contact from Commandline using Powershell and the Exchange Web Services API in a Mailbox in Exchange if a contact with the EmailAddress passed in Cant be resolved 
 
.DESCRIPTION 
  Create an Contact from Commandline using Powershell and the Exchange Web Services API in a Mailbox in Exchange if a contact with the EmailAddress passed in Cant be resolved 
 
 Requires the EWS Managed API from https://www.microsoft.com/en-us/download/details.aspx?id=42951

.EXAMPLE
 PS C:\>Create-Contact  -MailboxName user.name@domain.com -DisplayName DisplayName -FirstName John -LastName Doe -Credential (Get-Credential) -EmailAddress johndoe@domain.com -Company Company -Department Department -Office Office -BusinessPhone BusinessPhone -MobilePhone MobilePhone
 This Example creates an Contact in a Mailboxes Contact folder if a Contact with the EmailAddress passed in Cant be resolved 
#> 
function Create-Contact 
{ 
    [CmdletBinding()] 
    param( 
    	[Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
 		[Parameter(Position=1, Mandatory=$true)] [string]$DisplayName,
		[Parameter(Position=2, Mandatory=$true)] [string]$FirstName,
		[Parameter(Position=3, Mandatory=$true)] [string]$LastName,
		[Parameter(Position=4, Mandatory=$true)] [string]$EmailAddress,
		[Parameter(Position=5, Mandatory=$false)] [string]$Company,
		[Parameter(Position=6, Mandatory=$true)] [PSCredential]$Credentials,
		[Parameter(Position=7, Mandatory=$false)] [string]$Department,
		[Parameter(Position=8, Mandatory=$false)] [string]$Office,
		[Parameter(Position=9, Mandatory=$false)] [string]$BusinssPhone,
		[Parameter(Position=10, Mandatory=$false)] [string]$MobilePhone,
		[Parameter(Position=10, Mandatory=$false)] [string]$JobTitle,
		[Parameter(Position=11, Mandatory=$false)] [string]$Notes
    )  
 	Begin
		 {
		## Load Managed API dll  
		###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
		$EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")
		if (Test-Path $EWSDLL)
		    {
		    Import-Module $EWSDLL
		    }
		else
		    {
		    "$(get-date -format yyyyMMddHHmmss):"
		    "This script requires the EWS Managed API 1.2 or later."
		    "Please download and install the current version of the EWS Managed API from"
		    "http://go.microsoft.com/fwlink/?LinkId=255472"
		    ""
		    "Exiting Script."
		    exit
		    } 
  
		## Set Exchange Version  
		$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2  
		  
		## Create Exchange Service Object  
		$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)  
		  
		## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials  
		  
		#Credentials Option 1 using UPN for the windows Account  
		#$psCred = Get-Credential  
		$creds = New-Object System.Net.NetworkCredential($Credentials.UserName.ToString(),$Credentials.GetNetworkCredential().password.ToString())  
		$service.Credentials = $creds      
		#Credentials Option 2  
		#service.UseDefaultCredentials = $true  
		 #$service.TraceEnabled = $true
		## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
		  
		## Code From http://poshcode.org/624
		## Create a compilation environment
		$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
		$Compiler=$Provider.CreateCompiler()
		$Params=New-Object System.CodeDom.Compiler.CompilerParameters
		$Params.GenerateExecutable=$False
		$Params.GenerateInMemory=$True
		$Params.IncludeDebugInformation=$False
		$Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
		$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
		$TAAssembly=$TAResults.CompiledAssembly

		## We now create an instance of the TrustAll and attach it to the ServicePointManager
		$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
		[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

		## end code from http://poshcode.org/624
		  
		## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use  
		  
		#CAS URL Option 1 Autodiscover  
		$service.AutodiscoverUrl($MailboxName,{$true})  
		"Using CAS Server : " + $Service.url   
		   
		#CAS URL Option 2 Hardcoded  
		  
		#$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
		#$service.Url = $uri    
		  
		## Optional section for Exchange Impersonation  
		  
		#$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 

		# Bind to the Contacts Folder
		$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Contacts,$MailboxName)   
		$Contacts = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
	    $type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
		$type = $type.MakeGenericType("Microsoft.Exchange.WebServices.Data.FolderId" -as "Type")
		$ParentFolderIds = [Activator]::CreateInstance($type)
		$ParentFolderIds.Add($Contacts.Id)
		$Error.Clear();
		$ncCol = $service.ResolveName($EmailAddress,$ParentFolderIds,[Microsoft.Exchange.WebServices.Data.ResolveNameSearchLocation]::ContactsOnly,$true);
		if($Error.Count -eq 0){
	        if ($ncCol.Count -eq 0)  
	        {  
				$Contact = New-Object Microsoft.Exchange.WebServices.Data.Contact -ArgumentList $service 
				#Set the GivenName
				$Contact.GivenName = $FirstName
				#Set the LastName
				$Contact.Surname = $LastName
				#Set Subject  
				$Contact.Subject = $DisplayName
				$Contact.FileAs = $DisplayName
				$Contact.CompanyName = $Company
				$Contact.DisplayName = $DisplayName
				$Contact.Department = $Department
				$Contact.OfficeLocation = $Office
				$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone] = $BusinssPhone
				$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::MobilePhone] = $MobilePhone
				#Set the Location  
				$Contact.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1] = $EmailAddress
				#Set any Notes  
				$Contact.Body = $Notes
				$Contact.JobTitle = $JobTitle
		   		$Contact.Save($Contacts.Id)  
				Write-Host ("Contact Created")
			}
			else
			{		
				Write-Host ("Contact Already exists")
			}
		}
	}
}
Cheers
Glen
Free Windows Admin Tool Kit Click here and download it now
June 19th, 2015 11:09am

Here's a script that will create a contact in a contact folders if it doesn't exist you should be able to fill the rest of the logic in you need in around that

####################### 
<# 
.SYNOPSIS 
 Create an Contact from Commandline using Powershell and the Exchange Web Services API in a Mailbox in Exchange if a contact with the EmailAddress passed in Cant be resolved 
 
.DESCRIPTION 
  Create an Contact from Commandline using Powershell and the Exchange Web Services API in a Mailbox in Exchange if a contact with the EmailAddress passed in Cant be resolved 
 
 Requires the EWS Managed API from https://www.microsoft.com/en-us/download/details.aspx?id=42951

.EXAMPLE
 PS C:\>Create-Contact  -MailboxName user.name@domain.com -DisplayName DisplayName -FirstName John -LastName Doe -Credential (Get-Credential) -EmailAddress johndoe@domain.com -Company Company -Department Department -Office Office -BusinessPhone BusinessPhone -MobilePhone MobilePhone
 This Example creates an Contact in a Mailboxes Contact folder if a Contact with the EmailAddress passed in Cant be resolved 
#> 
function Create-Contact 
{ 
    [CmdletBinding()] 
    param( 
    	[Parameter(Position=0, Mandatory=$true)] [string]$MailboxName,
 		[Parameter(Position=1, Mandatory=$true)] [string]$DisplayName,
		[Parameter(Position=2, Mandatory=$true)] [string]$FirstName,
		[Parameter(Position=3, Mandatory=$true)] [string]$LastName,
		[Parameter(Position=4, Mandatory=$true)] [string]$EmailAddress,
		[Parameter(Position=5, Mandatory=$false)] [string]$Company,
		[Parameter(Position=6, Mandatory=$true)] [PSCredential]$Credentials,
		[Parameter(Position=7, Mandatory=$false)] [string]$Department,
		[Parameter(Position=8, Mandatory=$false)] [string]$Office,
		[Parameter(Position=9, Mandatory=$false)] [string]$BusinssPhone,
		[Parameter(Position=10, Mandatory=$false)] [string]$MobilePhone,
		[Parameter(Position=10, Mandatory=$false)] [string]$JobTitle,
		[Parameter(Position=11, Mandatory=$false)] [string]$Notes
    )  
 	Begin
		 {
		## Load Managed API dll  
		###CHECK FOR EWS MANAGED API, IF PRESENT IMPORT THE HIGHEST VERSION EWS DLL, ELSE EXIT
		$EWSDLL = (($(Get-ItemProperty -ErrorAction SilentlyContinue -Path Registry::$(Get-ChildItem -ErrorAction SilentlyContinue -Path 'Registry::HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Exchange\Web Services'|Sort-Object Name -Descending| Select-Object -First 1 -ExpandProperty Name)).'Install Directory') + "Microsoft.Exchange.WebServices.dll")
		if (Test-Path $EWSDLL)
		    {
		    Import-Module $EWSDLL
		    }
		else
		    {
		    "$(get-date -format yyyyMMddHHmmss):"
		    "This script requires the EWS Managed API 1.2 or later."
		    "Please download and install the current version of the EWS Managed API from"
		    "http://go.microsoft.com/fwlink/?LinkId=255472"
		    ""
		    "Exiting Script."
		    exit
		    } 
  
		## Set Exchange Version  
		$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP2  
		  
		## Create Exchange Service Object  
		$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService($ExchangeVersion)  
		  
		## Set Credentials to use two options are availible Option1 to use explict credentials or Option 2 use the Default (logged On) credentials  
		  
		#Credentials Option 1 using UPN for the windows Account  
		#$psCred = Get-Credential  
		$creds = New-Object System.Net.NetworkCredential($Credentials.UserName.ToString(),$Credentials.GetNetworkCredential().password.ToString())  
		$service.Credentials = $creds      
		#Credentials Option 2  
		#service.UseDefaultCredentials = $true  
		 #$service.TraceEnabled = $true
		## Choose to ignore any SSL Warning issues caused by Self Signed Certificates  
		  
		## Code From http://poshcode.org/624
		## Create a compilation environment
		$Provider=New-Object Microsoft.CSharp.CSharpCodeProvider
		$Compiler=$Provider.CreateCompiler()
		$Params=New-Object System.CodeDom.Compiler.CompilerParameters
		$Params.GenerateExecutable=$False
		$Params.GenerateInMemory=$True
		$Params.IncludeDebugInformation=$False
		$Params.ReferencedAssemblies.Add("System.DLL") | Out-Null

$TASource=@'
  namespace Local.ToolkitExtensions.Net.CertificatePolicy{
    public class TrustAll : System.Net.ICertificatePolicy {
      public TrustAll() { 
      }
      public bool CheckValidationResult(System.Net.ServicePoint sp,
        System.Security.Cryptography.X509Certificates.X509Certificate cert, 
        System.Net.WebRequest req, int problem) {
        return true;
      }
    }
  }
'@ 
		$TAResults=$Provider.CompileAssemblyFromSource($Params,$TASource)
		$TAAssembly=$TAResults.CompiledAssembly

		## We now create an instance of the TrustAll and attach it to the ServicePointManager
		$TrustAll=$TAAssembly.CreateInstance("Local.ToolkitExtensions.Net.CertificatePolicy.TrustAll")
		[System.Net.ServicePointManager]::CertificatePolicy=$TrustAll

		## end code from http://poshcode.org/624
		  
		## Set the URL of the CAS (Client Access Server) to use two options are availbe to use Autodiscover to find the CAS URL or Hardcode the CAS to use  
		  
		#CAS URL Option 1 Autodiscover  
		$service.AutodiscoverUrl($MailboxName,{$true})  
		"Using CAS Server : " + $Service.url   
		   
		#CAS URL Option 2 Hardcoded  
		  
		#$uri=[system.URI] "https://casservername/ews/exchange.asmx"  
		#$service.Url = $uri    
		  
		## Optional section for Exchange Impersonation  
		  
		#$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName) 

		# Bind to the Contacts Folder
		$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Contacts,$MailboxName)   
		$Contacts = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
	    $type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
		$type = $type.MakeGenericType("Microsoft.Exchange.WebServices.Data.FolderId" -as "Type")
		$ParentFolderIds = [Activator]::CreateInstance($type)
		$ParentFolderIds.Add($Contacts.Id)
		$Error.Clear();
		$ncCol = $service.ResolveName($EmailAddress,$ParentFolderIds,[Microsoft.Exchange.WebServices.Data.ResolveNameSearchLocation]::ContactsOnly,$true);
		if($Error.Count -eq 0){
	        if ($ncCol.Count -eq 0)  
	        {  
				$Contact = New-Object Microsoft.Exchange.WebServices.Data.Contact -ArgumentList $service 
				#Set the GivenName
				$Contact.GivenName = $FirstName
				#Set the LastName
				$Contact.Surname = $LastName
				#Set Subject  
				$Contact.Subject = $DisplayName
				$Contact.FileAs = $DisplayName
				$Contact.CompanyName = $Company
				$Contact.DisplayName = $DisplayName
				$Contact.Department = $Department
				$Contact.OfficeLocation = $Office
				$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone] = $BusinssPhone
				$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::MobilePhone] = $MobilePhone
				#Set the Location  
				$Contact.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1] = $EmailAddress
				#Set any Notes  
				$Contact.Body = $Notes
				$Contact.JobTitle = $JobTitle
		   		$Contact.Save($Contacts.Id)  
				Write-Host ("Contact Created")
			}
			else
			{		
				Write-Host ("Contact Already exists")
			}
		}
	}
}
Cheers
Glen
June 19th, 2015 11:09am

Thank you very much!!!

I will try to adapt this code to the code we have using, and write the code needed when the contact exists and will be neccesary to overwrite some data.

I'll try it in 10 days, when I have to go to the customer office.

Free Windows Admin Tool Kit Click here and download it now
June 19th, 2015 11:16am

Thanks for your answer, I just need something else:

	else
			{		
				Write-Host ("Contact Already exists")
			}

If the contact exists, I need to overwrite telefone number and corporate telephone number. How can I select the existing contact and overwrite that info?

Thanks so much.

July 10th, 2015 7:43am

What have you tired ? you should post what you have tried and always try yourself before asking question.

something like this should work

$ncCol.Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone] = $BusinssPhone
$ncCol.Contact.Update([Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite)
Cheers
Glen

Free Windows Admin Tool Kit Click here and download it now
July 12th, 2015 9:01pm

Thanks for your answer. Really, I hadn't tried anything because of my lack of Knowledgement in EWS. I can't find any documentation at all. When I made vbscript scripts, I found tons of documentation, but I haven't find any documentation about EWS, just blogs that talk about it, but not enough for me to learn.

I will try your solution.

July 13th, 2015 3:16am

Hi again,

After some test, I have found problems. I need to call this function from inside a script, so I have paste the code (simplified for test purposes), and called the function from inside the script. 

If I use this code to bind the contacts folder:

$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Contacts,$MailboxName) 

I get this error when trying to initialize the variable $Contacts.

Exception calling "Bind" with "2" argument(s): "The specified folder could not be found in the store."
At C:\scripts\Crear.ps1:111 char:65
+         $Contacts = [Microsoft.Exchange.WebServices.Data.Folder]::Bind <<<< ($service,$folderid)

I suppose that this is due to my version of Exchange: Spanish 2010, the folder Contacts doesn't exists, exists Contactos. But if I write the line:

$folderid= new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Contactos,$MailboxName) 

Then I get the error:

New-Object : Cannot find an overload for "FolderId" and the argument count: "2".

Apart from this, I want to make the things in a folder Inside the contacts folder (Contactos\Corporate Contacts). I have tried to do like that, changing ::Contacts by "Contactos\Corporate Contacts" with no luck.

I feel I'm near to find a solution for my needs, but I need some more help.

Thank you.


Free Windows Admin Tool Kit Click here and download it now
July 14th, 2015 6:00am

Hi again.

I have been able to solve the problem mentioned above. I have change the code to select the contacts folder and now I'm able to create non existing contacts into that folder.

However, I still have a problem: when the contact exists, I get an error when trying to update the Bussiness Telephone. The error is:

Cannot index into a null array.
At C:\scripts\Crear.ps1:75 char:33
+                 $ncCol.Contact.PhoneNumbers[ <<<< [Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BussinessPhone]
= $BussinssPhone
    + CategoryInfo          : InvalidOperation: (MobilePhone:PhoneNumberKey) [], RuntimeException

If I modify the line which is suppossed to make the change, trying to change, the Department like this:

$ncCol.Contact.Department = $Department I get this other error:

Property 'Department' cannot be found on this object; make sure it exists and is settable.

It seem as if the contact Object were not well referenced by $ncCol object, or as if it were referenced in some other way.

I will keep on investigating, but some help would be welcome.

:-)

July 14th, 2015 10:48am

>> "The specified folder could not be found in the store."

If you get that error it means you don't have rights to Folder you trying to access

For the other error try

$Contact = [Microsoft.Exchange.WebServices.Data.Contact]::Bind($service,$ncCol.Mailbox.Id)
$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone] = $BusinssPhone
$
Contact.Update([Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite
Cheers
Glen

Free Windows Admin Tool Kit Click here and download it now
July 14th, 2015 10:02pm

Thank you again.

This code drops the following error:

Exception calling "Bind" with "2" argument(s): "Value cannot be null.
Parameter name: itemId"
At C:\scripts\Crear.ps1:94 char:67
+                 $Contact = [Microsoft.Exchange.WebServices.Data.Contact]::Bind <<<< ($service,$ncCol.Mailbox.Id)

I put a line write-host $ncCol.count and another write-host $ncCol.Mailbox.Id and it writes 1 and blank.

I'm trying another way, when I finished the tests, I will inform. I still get errors. This is driving me crazy. :-(

July 15th, 2015 4:48am

I have made advances, but still there are things that are not working, so I still need some help.

Reading here and there, I have written the following script, which, at least, don't give any errors:

param([string]$Mailbox);

$Foldername="test"

function Create-Contact 
{ 
    [CmdletBinding()] 
    param([string]$MailboxName,
	[string]$DisplayName, 
	[string]$FirstName, 
	[string]$LastName, 
	[string]$EmailAddress, 
	[string]$Company, 
	[string]$Department, 
	[string]$Office, 
	[string]$BusinssPhone, 
	[string]$MobilePhone,
	[string]$Notes,
	[string]$JobTitle)  

    Begin
		{
			$EwsUrl = ([array](Get-WebServicesVirtualDirectory))[0].InternalURL.AbsoluteURI
			## Load Managed API dll  
			[void][Reflection.Assembly]::LoadFile("C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll");
			## Create Exchange Service Object  
			$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
			$service.UseDefaultCredentials = $true  
			$service.URL = New-Object Uri($EwsUrl);
			$service.ImpersonatedUserId = new-object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $MailboxName)
			# Bind to the Contacts Folder
			$RootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot)
			$RootFolder.Load()
			$FolderView = new-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)
			$ContactsFolderSearch = $RootFolder.FindFolders($FolderView) | Where {$_.DisplayName -eq $Foldername}
			$Contacts = [Microsoft.Exchange.WebServices.Data.ContactsFolder]::Bind($service,$ContactsFolderSearch.Id);
	        $type = ("System.Collections.Generic.List"+'`'+"1") -as "Type"
			$type = $type.MakeGenericType("Microsoft.Exchange.WebServices.Data.FolderId" -as "Type")
			$ParentFolderIds = [Activator]::CreateInstance($type)
			$ParentFolderIds.Add($Contacts.Id)
			$Error.Clear();
			$ncCol = $service.ResolveName($EmailAddress,$ParentFolderIds,[Microsoft.Exchange.WebServices.Data.ResolveNameSearchLocation]::ContactsOnly,$true);
		
			if($Error.Count -eq 0){
				if ($ncCol.Count -eq 0) #If I write-host $ncCol.count, it always shows 0, so it always enters here, the ResolveName query doesn't find the contact.  
				{  
					$Contact = New-Object Microsoft.Exchange.WebServices.Data.Contact -ArgumentList $service 
					#Set the GivenName
					$Contact.GivenName = $FirstName
					#Set the LastName
					$Contact.Surname = $LastName
					#Set Subject  
					$Contact.Subject = $DisplayName
					$Contact.FileAs = $DisplayName
					$Contact.CompanyName = $Company
					$Contact.DisplayName = $DisplayName
					$Contact.Department = $Department
					$Contact.OfficeLocation = $Office
					$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone] = $BusinssPhone
					$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::MobilePhone] = $MobilePhone
					#Set the Location  
					$Contact.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1] = $EmailAddress
					#Set any Notes  
					$Contact.Body = $Notes
					$Contact.JobTitle = $JobTitle
					$Contact.Save($Contacts.Id)  
				}
				else
				{
				#This is the code I want to execute if the contact is found in the folder
					$itemView = New-Object Microsoft.Exchange.WebServices.Data.ItemView(1000)
					$findItemResults = $service.FindItems($ContactsFolderSearch.ID, $itemView) 
					foreach ($Contact in $findItemResults.Items)
					{
						if ($Contact.DisplayName -eq $DisplayName ) {
							$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone] = $BusinssPhone
							$Contact.Save($Contacts.Id)
						}
					}
				}
			}
		}

}

$EwsUrl = ([array](Get-WebServicesVirtualDirectory))[0].InternalURL.AbsoluteURI

$UserMailbox  = Get-Mailbox $Mailbox

if (!$UserMailbox)
{
	throw "Mailbox $($Mailbox) not found";
	exit;
}

$EmailAddress2 = $UserMailbox.PrimarySMTPAddress

# Load EWS Managed API
[void][Reflection.Assembly]::LoadFile("C:\Program Files\Microsoft\Exchange\Web Services\1.2\Microsoft.Exchange.WebServices.dll");

$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
$service.UseDefaultCredentials = $true;
$service.URL = New-Object Uri($EwsUrl);

# Search for an existing copy of the Folder to store Org contacts 
$service.ImpersonatedUserId = New-Object Microsoft.Exchange.WebServices.Data.ImpersonatedUserId([Microsoft.Exchange.WebServices.Data.ConnectingIdType]::SmtpAddress, $EmailAddress2);
$RootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot)
$RootFolder.Load()
$FolderView = new-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)
$ContactsFolderSearch = $RootFolder.FindFolders($FolderView) | Where {$_.DisplayName -eq $FolderName}
if ($ContactsFolderSearch) #Check if the contactFolder exists
{
	$Users = get-user -Filter {WindowsEmailAddress -ne $null -and MobilePhone -ne $null -and WindowsEmailAddress -ne $EmailAddress2} 
	$Users = $Users | select DisplayName,FirstName,LastName,Title,Company,Department,WindowsEmailAddress,Phone,MobilePhone

	foreach ($ContactItem in $Users) {
	Create-Contact $Mailbox $ContactItem.DisplayName $ContactItem.FirstName $ContactItem.LastName $ContactItem.WindowsEmailAddress $ContactItem.Company $ContactItem.Department $ContactItem.OfficeLocation $ContactItem.Phone $ContactItem.MobilePhone $ContactItem.Body $ContactItem.Tittle
	}				
} 
else
{

	# Create new contacts folder
	$ContactsFolder = New-Object Microsoft.Exchange.WebServices.Data.ContactsFolder($service);
	$ContactsFolder.DisplayName = $FolderName
	$ContactsFolder.Save([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot)
	# Search for the new folder instance
	$RootFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,[Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::MsgFolderRoot)
	$RootFolder.Load()
	$FolderView = new-Object Microsoft.Exchange.WebServices.Data.FolderView(1000)
	$ContactsFolderSearch = $RootFolder.FindFolders($FolderView) | Where {$_.DisplayName -eq $FolderName}
	$ContactsFolder = [Microsoft.Exchange.WebServices.Data.ContactsFolder]::Bind($service,$ContactsFolderSearch.Id);
	$Users = get-user -Filter {WindowsEmailAddress -ne $null -and MobilePhone -ne $null -and WindowsEmailAddress -ne $EmailAddress2} 
	$Users = $Users | select DisplayName,FirstName,LastName,Title,Company,Department,WindowsEmailAddress,Phone,MobilePhone

	#Once created the folder, write the contacts in it

	foreach ($ContactItem in $Users) { 
	Create-Contact $Mailbox $ContactItem.DisplayName $ContactItem.FirstName $ContactItem.LastName $ContactItem.WindowsEmailAddress $ContactItem.Company $ContactItem.Department $ContactItem.OfficeLocation $ContactItem.Phone $ContactItem.MobilePhone $ContactItem.Body $ContactItem.Tittle
	}				
}

I call the script passing as param the email address of the user to who I will create the contact folder "test", and copy the GAL contacts in it. 

When I run it for the first time, it works well: creates the folder and copy the GAL contacts into it.

But the second time that runs, instead of copying new GAL contacts and leave the existing contacts without modification except by the Bussiness Phone number, as I want, it copies again all the contacts, resulting in all entries duplicated.

As I write in the code coments, the line 

$ncCol = $service.ResolveName($EmailAddress,$ParentFolderIds,[Microsoft.Exchange.WebServices.Data.ResolveNameSearchLocation]::ContactsOnly,$true);

is not finding the contact in the contact folder, because a write-host $ncCol.count after the line, shows always 0.

And the problem is not in the code: if I pass the search parameter to $EmailAddress as a string like "test@test.com", the contact is found. The problem is something strange: if I do a loop through all the contacts and write-host this:

$Contact.EmailAddresses[[Microsoft.Exchange.WebServices.Data.EmailAddressKey]::EmailAddress1]

what I see is not email address as is suppossed to be (i.e "test@test.com"): what I get is something like this:

/o=Persan Central/ou=Primer grupo administrativo/cn=Recipients/cn=fjfonseca

But in Outlook, the contact shows a correct email address.

Any clue?


Free Windows Admin Tool Kit Click here and download it now
July 15th, 2015 8:27am

You can try this

Grab the module code from https://github.com/gscales/Powershell-Scripts/raw/master/EWSContacts/EWSContactFunctions.zip

then use

Import-Module .\EWSContactFunctions.ps1 -Force

$MailboxName = "usermail@domain.com"
$FolderPath = "\Contacts"
$ContactEmail = "timp22@domain.com"
$PhoneNumber = 3342211


$Contact = Get-Contact -MailboxName $MailboxName -EmailAddress $ContactEmail -Folder $FolderPath
if($Contact){
	$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone] = $PhoneNumber
	$Contact.Update([Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite)
	Write-Host ("Updated")
}
else{
	Create-Contact -MailboxName $MailboxName -EmailAddress $ContactEmail -FirstName Balh -LastName Blah -DisplayName 'Blah blah'
	
}
Cheers
Glen

July 16th, 2015 1:29am

You can try this

Grab the module code from https://github.com/gscales/Powershell-Scripts/raw/master/EWSContacts/EWSContactFunctions.zip

then use

Import-Module .\EWSContactFunctions.ps1 -Force

$MailboxName = "usermail@domain.com"
$FolderPath = "\Contacts"
$ContactEmail = "timp22@domain.com"
$PhoneNumber = 3342211


$Contact = Get-Contact -MailboxName $MailboxName -EmailAddress $ContactEmail -Folder $FolderPath
if($Contact){
	$Contact.PhoneNumbers[[Microsoft.Exchange.WebServices.Data.PhoneNumberKey]::BusinessPhone] = $PhoneNumber
	$Contact.Update([Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite)
	Write-Host ("Updated")
}
else{
	Create-Contact -MailboxName $MailboxName -EmailAddress $ContactEmail -FirstName Balh -LastName Blah -DisplayName 'Blah blah'
	
}
Cheers
Glen

Free Windows Admin Tool Kit Click here and download it now
July 16th, 2015 5:28am

Thank you so much, Glen.

This solution appears to work, with just a consideration: if the contact exists and the bussiness phone has not changed in user contacts folder, it throws an error telling that update AllwaysOverride is not valid. So I have inserted code to check if the bussiness phone in the GAL is different from the user's contact folder. If is the same, no need of update, so it pass to the following contact.

It works with hardcoded data. Now I have to put in context with the GAL enumeration. Let's see if the emailadress1 problem is solved.

I will let you know. By now, thank you very much.

July 16th, 2015 10:08am

Hi again.

After some modifications to the script that calls the function, finnally is working well. Not only modifies the bussines telephone number, but department, company, jobtitle. 

For the A qualification, I will try to delete from the user contact folder those users that are not in the GAL, but that is less important.

Glen, I don't know how to thank your huge help. You are not conscious of how great has been your help for me.

Thank you very very much.

Free Windows Admin Tool Kit Click here and download it now
July 16th, 2015 1:01pm

This topic is archived. No further replies will be accepted.

Other recent topics Other recent topics