Skip to main content

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.

Popular posts from this blog

Export calendar Items to a CSV file using EWS and Powershell

Somebody asked about this last week and while I have a lot of EWS scripts that do access the Calendar I didn't have a simple example that just exported a list of the Calendar events with relevant information to a CSV file so here it is.

I've talked on this one before in this howto  but when you query the calendar folder using EWS you need to use a CalendarView which will expand any recurring appointments in a calendar. There are some limits when you use a calendarview in that you can only return a maximum of 2 years of appointments at a time and paging will limit the max number of items to 1000 per call. So if you have a calendar with a very large number of appointments you need to break your query into small date time blocks. In this example script I'm just grabbing the next 7 days of appointments if you want to query a longer period you need to adjust the following lines (keeping in mind what I just mentioned)

#Define Date to Query
$StartDate = (Get-Date)
$EndDate = (Ge…

EWS Managed API and Powershell How-To series Part 1

I thought I'd start the year with a series of posts that goes back over the basics of using the EWS Managed API from Powershell and provides a modular remarked example that you can easily cut and paste to build your own scripts. Along the way in this series I'll show a whole bunch of examples around specific things.

As a starting point for versions this will be Powershell Version 2.0  and the EWS Managed API 1.1 (which will soon change to 1.2 once released) http://www.microsoft.com/download/en/details.aspx?id=13480.

The starting point for any EWS script your going to write is connecting to Exchange for which there are three important pieces of information you will need. Firstly you need to know the version of Exchange your running in this script its going to be held in the following variable

$ExchangeVersion = [Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2010_SP1

Other valid values for Exchange 2007 would be

$ExchangeVersion = [Microsoft.Exchange.WebServices.…

Writing a simple scripted process to download attachmentts in Exchange 2007/ 2010 using the EWS Managed API

Every complicated thing in life is made up of smaller simpler building blocks, when it comes to writing a script (or any code really) the more of these little building blocks you have to figure out the more the process of solving a problem can become bewildering. The Internet generally provides you with lots of half eaten sandwiches of information something someone else has taken a bite out but a lot of the time half done, and as with any code its usefulness declines over time as new and better API's and methods are derived. In this post I'm going to go through a simple scripted process that hopefully covers a few more of these smaller building blocks that you might face when asked to come up with a simple costless solution to perform an automated business function with a script.

So the process im going to look at is one that comes up a lot and that is you have an Email that comes into to certain mailbox every day with a certain subject in my case "Daily Export" this …
All sample scripts and source code is provided by for illustrative purposes only. All examples are untested in different environments and therefore, I cannot guarantee or imply reliability, serviceability, or function of these programs.

All code contained herein is provided to you "AS IS" without any warranties of any kind. The implied warranties of non-infringement, merchantability and fitness for a particular purpose are expressly disclaimed.