Exchange Web Service (EWS) et Powershell : exemple de script

Bonjour,

Aujourd’hui je vous présente un exemple de code Powershell utilisant les types et fonctionnalités de l’Exchange Web Service Managed API (EWS API 1.1)

Le script suivant permet de parcourir un dossier d’email en particulier. Il check si les éléments possèdent un ID personnalisé (qui est une propriété étendue). Dans le cas contraire, il en affecte une (génération d’un GUID)

Voici le code:

$usertoQuery = "EMAILADDRESS"
 
$dllpath = "XXX\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
 
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1)
 
$service.Credentials = new-object Microsoft.Exchange.WebServices.Data.WebCredentials("LOGIN","PWD","DOMAIN")
$service.Url = new-object Uri("http://URL/EWS/Exchange.asmx");
 
$svFldid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::SearchFolders,$MailboxName)
$delFldid = [Microsoft.Exchange.WebServices.Data.DeleteMode]::HardDelete
 
$fvFolderView = new-object Microsoft.Exchange.WebServices.Data.FolderView(1000)
 
$folders = $service.findfolders($svFldid,$fvFolderView)
$ExtendedProp = new-object Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition([Microsoft.Exchange.WebServices.Data.DefaultExtendedPropertySet]::PublicStrings, "MyCustomID", [Microsoft.Exchange.WebServices.Data.MapiPropertyType]::String)
$ExtendedProp
$Propset = new-object Microsoft.Exchange.WebServices.Data.PropertySet([Microsoft.Exchange.WebServices.Data.BasePropertySet]::FirstClassProperties, $ExtendedProp)
 
foreach ($folder in $folders)
{
    if ($folder.displayName -eq "FOLDERNAME_I_WANT_TO_CHECK")
    {
		"We are in the correct folder"
         $fvItemView = new-object Microsoft.Exchange.WebServices.Data.ItemView(10000)
 
		 $items = $service.FindItems($folder.Id,$fvItemView)	
		 #Don't show any result for the next line
		 $service.LoadPropertiesForItems($items, $Propset)
		 foreach ($item in $items)
		 {
			"**Subject** : " 
			$item.Subject
			"**Number of Extended Properties**: " 
			$item.ExtendedProperties.Count		
 
			$a = 0
 
			foreach ($extendedProperty in $item.ExtendedProperties)
			{
				if ($extendedProperty.PropertyDefinition.Name -eq $ExtendedProp.Name)
				{					
					$a = 1
					"Break (Value = " + $extendedProperty.Value + ")"
					break;						
				}		
			}
 
			if ($a -eq 0)
			{			
				$g1 = [Guid]::NewGuid()
				$item.SetExtendedProperty($ExtendedProp, $g1.ToString())
				"Guid = " + $g1
				"ValueGuid added!"
				$item.Update([Microsoft.Exchange.WebServices.Data.ConflictResolutionMode]::AlwaysOverwrite)
				"Item saved"
			}
		 }	 
    }
}

Et voila une base pour maitriser (un peu) la sémantique Powershell et manipuler l’api EWS d’une autre façon!

Leave a Reply

Your email address will not be published. Required fields are marked *