Friday, December 08, 2006

Scripting Exchange Web Services (2007) with VBS and Powershell

I’ve been playing around with the new Exchange 2007 Web Services and thought I would share a few scripts. With a lot of API’s being deemphasized or disappearing completely in Exchange 2007, Exchange Web Services are the brave new world that confronts people who want to develop applications that run against an Exchange 2007 server. Like any other WebService EWS allows you to invoke different methods which will perform specific tasks by sending SOAP messages that contain certain properties and then receiving specifically formatted responses. For a scripting point of view it’s pretty easy firstly you need to authenticate the default authentication is NTLM so there is no need to worry about FBA synthetic logons and then it’s just a matter of posting a XML formatted SOAP message. If your familiar with using WebDAV the underlying methods you use are the same but the requests and responses are very different. Lets start with a simple send email example.

smSoapMessage = "<?xml version='1.0' encoding='utf-8'?>" _
& "<soap:Envelope xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"" " _
& " xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema"">" _
& "<soap:Body><CreateItem MessageDisposition=""SendAndSaveCopy"" " _
& " xmlns=""http://schemas.microsoft.com/exchange/services/2006/messages""> " _
& "<SavedItemFolderId><DistinguishedFolderId Id=""sentitems""
xmlns=""http://schemas.microsoft.com/exchange/services/2006/types""/>" _
& "</SavedItemFolderId><Items><Message
xmlns=""http://schemas.microsoft.com/exchange/services/2006/types"">" _
& "<ItemClass>IPM.Note</ItemClass><Subject>" & stSubjet & "</Subject><Body
BodyType=""Text"">" & ebEmailBody & "</Body><ToRecipients>" _
& "<Mailbox><EmailAddress>" & EmailAddress &
"</EmailAddress></Mailbox></ToRecipients></Message></Items>" _
& "</CreateItem></soap:Body></soap:Envelope>"
set req = createobject("microsoft.xmlhttp")


The first thing you need to do is build a SOAP message for scripting I prefer to just to build the message manually as a string. You could use the XMLDOM object but this requires a lot more lines of code and complexity. This soap message is a CreateItem request that creates a message and saves it in the SentItems folder. The MessageDisposition Attribute controls how the Exchange server goes about handling this message after its received in this instance it is sent and also a copy is saved to the folder listed in the DistinguishedFolderId element.


set req = createobject("microsoft.xmlhttp")
req.Open "post", "http://" & servername & "/ews/Exchange.asmx", False,"domain\user", "password"
req.setRequestHeader "Content-Type", "text/xml"
req.setRequestHeader "translate", "F"
req.send smSoapMessage
wscript.echo req.status
wscript.echo
wscript.echo req.responsetext

The IIS virtual directory you use to access the Exchange Webservice is http://Servername/EWS. If your send is successful you will see a Status of 200 returned if not you usually get a 50x error message. The response messages are usually pretty good for diagnosing what your doing wrong (its generally a formatting issue with the soap message).

Another method of interest is the GetFolder method which is roughly equivalent to a propfind in WebDAV in that it allows you to retrieve properties from a folder. Some properties of interest might be things like the foldersize or the unread message count on the inbox. The following is a SOAP request that can be used to get the unread message count on the inbox. (Switching from VBS to Powershell this time)

$smSoapMessage = "<?xml version='1.0' encoding='utf-8'?>" `
+ "<soap:Envelope xmlns:soap=`"http://schemas.xmlsoap.org/soap/envelope/`" " `
+ " xmlns:xsi=`"http://www.w3.org/2001/XMLSchema-instance`" xmlns:xsd=`"http://www.w3.org/2001/XMLSchema`"" `
+ " xmlns:t=`"http://schemas.microsoft.com/exchange/services/2006/types`" >" `
+ "<soap:Body>" `
+ "<GetFolder xmlns=`"http://schemas.microsoft.com/exchange/services/2006/messages`"
" `
+ " xmlns:t=`"http://schemas.microsoft.com/exchange/services/2006/types`"> " `
+ "<FolderShape> " `
+ "<t:BaseShape>Default</t:BaseShape> " `
+ "</FolderShape> " `
+ "<FolderIds> " `
+ "<t:DistinguishedFolderId Id=`"inbox`"/> " `
+ "</FolderIds> " `
+ "</GetFolder> " `
+ "</soap:Body></soap:Envelope>"


The BaseShape element controls which properties are returned by the query the default set generally contains all the properties you need to do basic tasks (including the unread count). But if you want to get all the properties or include additional properties there are other elements to do this job.

$servername = "ws03r2eeexchlcs"
$strRootURI = "http://" + $servername + "/ews/Exchange.asmx"
$WDRequest = [System.Net.WebRequest]::Create($strRootURI)
$WDRequest.ContentType = "text/xml"
$WDRequest.Headers.Add("Translate", "F")
$WDRequest.Method = "Post"
$WDRequest.Credentials = $cdUsrCredentials
$bytes = [System.Text.Encoding]::UTF8.GetBytes($smSoapMessage)
$WDRequest.ContentLength = $bytes.Length
$RequestStream = $WDRequest.GetRequestStream()
$RequestStream.Write($bytes, 0, $bytes.Length)
$RequestStream.Close()
$WDResponse = $WDRequest.GetResponse()
$ResponseStream = $WDResponse.GetResponseStream()
$ResponseXmlDoc = new-object System.Xml.XmlDocument
$ResponseXmlDoc.Load($ResponseStream)
$UreadNameNodes = @($ResponseXmlDoc.GetElementsByTagName("t:UnreadCount"))
"Number of Unread Email : " + $UreadNameNodes[0].'#text'

The one important thing here when you are looking at the results returned by the EWS and your using getElementsByTagName method in Powershell is make sure you use the @ array specifier In front of the method call or you wont be able to index into the collection and access the elements. Authentication in Powershell can be handled in two ways if you want to specify which credentials to use you can use a credential object with a line such as

$cdUsrCredentials = new-object System.Net.NetworkCredential("Administrator", "Evaluation1", "CONTOSO")

And then set the request object to use those credentials

$WDRequest.Credentials = $cdUsrCredentials

Or you can specify to use the credentials from the user context that is invoking the script by setting the request object like

$WDRequest.UseDefaultCredentials = $True

The Last thing to look at is the restriction element this allows you to specify which items you want to return. So if you where to use the FindItem method to list items in your inbox and you wanted to just return those items that where unread and only 24 hours old then you could use something like this in the restriction section of the SOAP message.


+ "<Restriction>" `
+ "<t:And>" `
+ "<t:IsEqualTo>" `
+ "<t:FieldURI FieldURI=`"message:IsRead`"/>"`
+ "<t:FieldURIOrConstant>" `
+ "<t:Constant Value=`"0`"/>" `
+ "</t:FieldURIOrConstant>" `
+ "</t:IsEqualTo>" `
+ "<t:IsGreaterThanOrEqualTo>" `
+ "<t:FieldURI FieldURI=`"item:DateTimeSent`"/>"`
+ "<t:FieldURIOrConstant>" `
+ "<t:Constant Value=`"" + $datetimetoquery.ToUniversalTime().AddDays(-1).ToString("yyyy-MM-ddThh:mm:ssZ")
+ "`"/>"`
+ "</t:FieldURIOrConstant>"`
+ "</t:IsGreaterThanOrEqualTo>"`
+ "</t:And>"`
+ "</Restriction>"`


Like Exchange 200x when you query the Exchange store with a Datetime range that datetime range should be converted to the ISO dateformat and also because Exchange stores date and times in UTC you should convert the date and time you want to query for into UTC before you use it (and also convert the returned times back into Local time so they make sense). Powershell lets you tap into the .NET time conversion functions which makes things a lot simpler then they where in VBS.

I’ve created 4 scripts all up both in VBS and Powershell the scripts do the following tasks

Sendews : Sends a message using EWS
Ureadews : Reads the UnreadCount property of the inbox
Shureadews : Shows the Time,From,Subject and size of all unread messages in the inbox
Shureadewstday Shows the Time,From,Subject and size of all unread messages in the inbox just for the past 24 hours

I’ve put a downloadable copy of the script here.