Skip to main content

Twitter a Exchange Calendar using Powershell and EWS - Exchange 2007

Micro-Blogging is one of the Web 2.0 technologies that has been getting a bit of run of late its one of the tools a seemingly new breed of politicians are using to garner support and awareness of their movements. But its also used by a growing number of everyday people and businesses as a method of pervaying certain messages and other sometimes seemly useless pieces of information. Maybe one of the keys to twitter's success is it fills the gap between availibilty and straight calendaring. I think the scope of what could be done with twitter when you start to intergrate this into traditional communication technology should see this technology expand even more (well as long as we get some creative people pushing the limits).

Exchange mostly provides the same type of information in different formats so using the Twitter API and the Exchange API's you can start to combine the functionality of both systems to start providing different new funcationality. Eg in this sample Im using a script to query an Exchange calendar and then take the text from the current appointment (if there is one) trim it to 140 characters and then post this as a Twitter update. There's logic in the script to first check the current twitter status so the script can be run at intervals and ensure that multiple updates wont be sent for multiple appointments. If you have more then one appointment scheduled at the same time it will just use the first.

So what could you use it for ?.. well any compay,club or small group who has a calendar or events can create twitter feed for these event by simply placeing the events in a Exchange calendar and then let the script read and twitter the status updates. Most of our lives are scripted by our calendar anyway so here a way to save on typing.

How does it work.

There are already a few good Powershell twitter scripts so i grabbed some code out of Mike Ormonds's Sample and started working in some other code. The first thing the scirpt does is goes and grabs the current twitter status. It then goes and queries the mailbox calendar to see if there are any appointments that are in the current time frame. If it find one it then posts the subject of the appointment as a twitter status update. To do the Exchange side I've use Exchange Web Services via some code i've packed into my EWSUtil powershell library (actually im reusing the stuff from the RSS feed script).

Making it work

To make this work you first need a twitter account and a Exchange 2007 Mailbox you need to put your twitter username and password in the following varibles

$twitterusername = "username"
$twitterpassword = "password"

Then put the Email address of the mailbox with the calendar you want to pull the data from and the Exchange Username and password to access this mailbox (or you can use EWS impersonation if you wanted to agregate several mailboxes) in the following varibles.

$emEmailAddress = "twittest@domain.com"
$userName = "twittest"
$password = "Password"
$domain = "domain"

In the

$ExchangeServername = "servername"

put the CAS Servername

If your using a cloud mailbox on Microsoftonline set the domain to blank and use something like (I've built this using a BPOS mailbox)

$emEmailAddress = "twittest@youdomain.microsoftonline.com"
$userName = "twittest@youdomain.microsoftonline.com"
$password = "youpassword"
$domain = ""

To use this you need the EWSUtil library I've put a download of this script here the script itself looks like (note this script is pretty alpha issh so do your own testing first)

$twitterusername = "username"
$twitterpassword = "password"
$ExchangeServername = "servername"
$emEmailAddress = "twittest@domain.com"
$userName = "twittest"
$password = "Password"
$domain = "domain"

function updateTwiterStatus($PostString){

$tweetstring = [String]::Format("status={0}", $PostString )
[System.Net.ServicePointManager]::Expect100Continue = $false
$request = [System.Net.WebRequest]::Create("http://twitter.com/statuses/update.xml")
$request.Credentials = new-object System.Net.NetworkCredential($twitterusername,$twitterpassword)
$request.Method = "POST"
$request.ContentType = "application/x-www-form-urlencoded"
$formdata = [System.Text.Encoding]::UTF8.GetBytes($tweetstring)
$request.ContentLength = $formdata.Length
$requestStream = $request.GetRequestStream()
$requestStream.Write($formdata, 0, $formdata.Length)
$requestStream.Close()
$response = $request.GetResponse()
$reader = new-object System.IO.StreamReader($response.GetResponseStream())
$returnvalue = $reader.ReadToEnd()
$reader.Close()

}

function GetTwitterStatus(){
[System.Net.ServicePointManager]::Expect100Continue = $false
$request = [System.Net.WebRequest]::Create("http://twitter.com/users/show/" + $twitterusername)
$request.Credentials = new-object System.Net.NetworkCredential($twitterusername,$twitterpassword)
$request.Method = "GET"
$request.ContentType = "application/x-www-form-urlencoded"
$response = $request.GetResponse()
$ResponseStream = $response.GetResponseStream()
$ResponseXmlDoc = new-object System.Xml.XmlDocument
$ResponseXmlDoc.Load($ResponseStream)
$StatusNodes = @($ResponseXmlDoc.getElementsByTagName("status"))
$returnStatus = $StatusNodes[0].text
$ResponseXmlDoc.Save("c:\dd.xml")
return $returnStatus.ToString()
}


$casURL = "https://" + $ExchangeServername + "/EWS/Exchange.asmx"
[void][Reflection.Assembly]::LoadFile("C:\temp\EWSUtil.dll")
$ewc = new-object EWSUtil.EWSConnection($emEmailAddress,$false, $userName, $password,$domain, $casURL)
$drDuration = new-object EWSUtil.EWS.Duration
$drDuration.StartTime = [DateTime]::UtcNow
$drDuration.EndTime = [DateTime]::UtcNow.AddMinutes(15)
$upset = 0
[EWSUtil.EWS.DistinguishedFolderIdType] $dType = new-object EWSUtil.EWS.DistinguishedFolderIdType
$dType.Id = [EWSUtil.EWS.DistinguishedFolderIdNameType]::calendar
$qfolder = new-object EWSUtil.QueryFolder($ewc,$dType, $drDuration,$false,$true)
foreach ($item in $qfolder.fiFolderItems){
if ($item.Location -ne $null){
$twitString = $item.Subject.ToString() + " " + $item.Location.ToString()
}
else{
$twitString = $item.Subject.ToString()
}
if ($twitString.Length -gt 140){$twitString = $twitString.Substring(0,139)}
[String]$currentStatus = GetTwitterStatus
$twitString = $twitString.Substring(0,$twitString.length-1)
write-host $twitString.ToLower().ToString()
write-host $currentStatus.ToLower().ToString()
if ($currentStatus.ToLower().ToString() -ne $twitString.ToLower().ToString()){
if ($statusup -ne 3){$statusup = 1}
$upset = 1
}
else{
$statusup = 3
}
}
if ($statusup -eq 1){
updateTwiterStatus($twitString)
"Twitter Status Updated"
}
else {"Nothing changed since last update"}

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

Downloading a shared file from Onedrive for business using Powershell

I thought I'd quickly share this script I came up with to download a file that was shared using One Drive for Business (which is SharePoint under the covers) with Powershell. The following script takes a OneDrive for business URL which would look like https://mydom-my.sharepoint.com/personal/gscales_domain_com/Documents/Email%20attachments/filename.txt This script is pretty simple it uses the SharePoint CSOM (Client side object Model) which it loads in the first line. It uses the URI object to separate the host and relative URL which the CSOM requires and also the SharePointOnlineCredentials object to handle the Office365 SharePoint online authentication. The following script is a function that take the OneDrive URL, Credentials for Office365 and path you want to download the file to and downloads the file. eg to run the script you would use something like ./spdownload.ps1 ' https://mydom-my.sharepoint.com/personal/gscales_domain_com/Documents/Email%20attachments/filena

The MailboxConcurrency limit and using Batching in the Microsoft Graph API

If your getting an error such as Application is over its MailboxConcurrency limit while using the Microsoft Graph API this post may help you understand why. Background   The Mailbox  concurrency limit when your using the Graph API is 4 as per https://docs.microsoft.com/en-us/graph/throttling#outlook-service-limits . This is evaluated for each app ID and mailbox combination so this means you can have different apps running under the same credentials and the poor behavior of one won't cause the other to be throttled. If you compared that to EWS you could have up to 27 concurrent connections but they are shared across all apps on a first come first served basis. Batching Batching in the Graph API is a way of combining multiple requests into a single HTTP request. Batching in the Exchange Mail API's EWS and MAPI has been around for a long time and its common, for email Apps to process large numbers of smaller items for a variety of reasons.  Batching in the Graph is limited to a m
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.