Wednesday, March 31, 2010

FreeBusy Board for the Exchange EWS Managed API using Powershell

This is a port of one of my previous EWS powershell scripts that produces a freebusy board using EWS. The advantage of this one is that it uses the EWS Managed API and it also exposes the private enums on the appointment details so it avoids publishing any appointments that are marked as private. For those familiar with using the EWS Managed API its also a lot easier to customize to your own needs. For details on how and why it work please see the previous post linked up the top.

I’ve put a download the code here the code itself look like

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)

$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind

$service.AutodiscoverUrl($aceuser.mail.ToString())

$mbHash = @{ }

$tmValHash = @{ }
$tidx = 0
for($vsStartTime=[DateTime]::Parse([DateTime]::Now.ToString("yyyy-MM-dd 0:00"));$vsStartTime -lt [DateTime]::Parse([DateTime]::Now.ToString("yyyy-MM-dd 0:00")).AddDays(1);$vsStartTime = $vsStartTime.AddMinutes(30)){
$tmValHash.add($vsStartTime.ToString("HH:mm"),$tidx)
$tidx++
}

get-mailbox -ResultSize unlimited | foreach-object{
if ($mbHash.ContainsKey($_.WindowsEmailAddress.ToString()) -eq $false){
$mbHash.Add($_.WindowsEmailAddress.ToString(),$_.DisplayName)
}
}
$Attendeesbatch = [activator]::createinstance(([type]'System.Collections.Generic.List`1').makegenerictype([Microsoft.Exchange.WebServices.Data.AttendeeInfo]))

$StartTime = [DateTime]::Parse([DateTime]::Now.ToString("yyyy-MM-dd 0:00"))
$EndTime = $StartTime.AddDays(1)


$displayStartTime = [DateTime]::Parse([DateTime]::Now.ToString("yyyy-MM-dd 08:30"))
$displayEndTime = [DateTime]::Parse([DateTime]::Now.ToString("yyyy-MM-dd 17:30"))

$drDuration = new-object Microsoft.Exchange.WebServices.Data.TimeWindow($StartTime,$EndTime)
$AvailabilityOptions = new-object Microsoft.Exchange.WebServices.Data.AvailabilityOptions
$AvailabilityOptions.RequestedFreeBusyView = [Microsoft.Exchange.WebServices.Data.FreeBusyViewType]::DetailedMerged

$batchsize = 100
$bcount = 0
$bresult = @()
if ($mbHash.Count -ne 0){
$mbHash.GetEnumerator() | Sort Value | foreach-object {
if ($bcount -ne $batchsize){
$Attendee1 = new-object Microsoft.Exchange.WebServices.Data.AttendeeInfo($_.Key)
$Attendeesbatch.add($Attendee1)
$bcount++
}
else{
$availresponse = $service.GetUserAvailability($Attendeesbatch,$drDuration,[Microsoft.Exchange.WebServices.Data.AvailabilityData]::FreeBusy,$AvailabilityOptions)
foreach($avail in $availresponse.AttendeesAvailability.OverallResult){$bresult += $avail}
$Attendeesbatch = [activator]::createinstance(([type]'System.Collections.Generic.List`1').makegenerictype([Microsoft.Exchange.WebServices.Data.AttendeeInfo]))
$bcount = 0
$Attendee1 = new-object Microsoft.Exchange.WebServices.Data.AttendeeInfo($_.Key)
$Attendeesbatch.add($Attendee1)
$bcount++
}
}
}
$availresponse = $service.GetUserAvailability($Attendeesbatch,$drDuration,[Microsoft.Exchange.WebServices.Data.AvailabilityData]::FreeBusy,$AvailabilityOptions)
$usrIdx = 0
$frow = $true
foreach($res in $availresponse.AttendeesAvailability){
if ($frow -eq $true){
$fbBoard = $fbBoard + "<table><tr bgcolor=`"#95aedc`">" +"`r`n"
$fbBoard = $fbBoard + "<td align=`"center`" style=`"width=200;`" ><b>User</b></td>" +"`r`n"
for($stime = $displayStartTime;$stime -lt $displayEndTime;$stime = $stime.AddMinutes(30)){
$fbBoard = $fbBoard + "<td align=`"center`" style=`"width=50;`" ><b>" + $stime.ToString("HH:mm") + "</b></td>" +"`r`n"
}
$fbBoard = $fbBoard + "</tr>" + "`r`n"
$frow = $false
}
for($stime = $displayStartTime;$stime -lt $displayEndTime;$stime = $stime.AddMinutes(30)){
if ($stime -eq $displayStartTime){
$fbBoard = $fbBoard + "<td bgcolor=`"#CFECEC`"><b>" + $mbHash[$Attendeesbatch[$usrIdx].SmtpAddress] + "</b></td>" + "`r`n"
}
$title = "title="
if ($res.MergedFreeBusyStatus[$tmValHash[$stime.ToString("HH:mm")]] -ne $null){
$gdet = $false
$FbValu = $res.MergedFreeBusyStatus[$tmValHash[$stime.ToString("HH:mm")]]
switch($FbValu.ToString()){
"Free" {$bgColour = "bgcolor=`"#41A317`""}
"Tentative" {$bgColour = "bgcolor=`"#52F3FF`""
$gdet = $true
}
"Busy" {$bgColour = "bgcolor=`"#153E7E`""
$gdet = $true
}
"OOF" {$bgColour = "bgcolor=`"#4E387E`""
$gdet = $true
}
"NoData" {$bgColour = "bgcolor=`"#98AFC7`""}
"N/A" {$bgColour = "bgcolor=`"#98AFC7`""}
}
if ($gdet -eq $true){
if ($res.CalendarEvents.Count -ne 0){
for($ci=0;$ci -lt $res.CalendarEvents.Count;$ci++){
if ($res.CalendarEvents[$ci].StartTime -ge $stime -band $stime -le $res.CalendarEvents[$ci].EndTime){
if($res.CalendarEvents[$ci].Details.IsPrivate -eq $False){
$subject = ""
$location = ""
if ($res.CalendarEvents[$ci].Details.Subject -ne $null){
$subject = $res.CalendarEvents[$ci].Details.Subject.ToString()
}
if ($res.CalendarEvents[$ci].Details.Location -ne $null){
$location = $res.CalendarEvents[$ci].Details.Location.ToString()
}
$title = $title + "`"" + $subject + " " + $location + "`" "
}
}
}
}
}

}

else{
$bgColour = "bgcolor=`"#98AFC7`""
}
if($title -ne "title="){
$fbBoard = $fbBoard + "<td " + $bgColour + " " + $title + "></td>" + "`r`n"
}
else{
$fbBoard = $fbBoard + "<td " + $bgColour + "></td>" + "`r`n"
}

}
$fbBoard = $fbBoard + "</tr>" + "`r`n"
$usrIdx++
}
$fbBoard = $fbBoard + "</table>" + " "
$fbBoard | out-file "c:\fbboard.htm"

Monday, March 15, 2010

NDR hunt using the EWS Managed API and Powershell to find and delete NDR messages in a mailbox

While this is the time of year that we are more often concerned with hunting down round chocolate things to stuff in our gobs one endearing task most mail administrators must deal with is the management of NDR messages. NDR’s while exceedingly useful at the time a problem occurs once this time has passed their usefulness falls and they tend to become redundant fragments of information that can clutter a mailbox. Especially if you are copying these items to an administrator mailbox you can soon see the mailbox size and item count shot up exponentially if cleanups aren’t occurring on a frequent basis. Because deleting email can be a very tedious process this is something that can be easily scripted using the EWS Managed API and powershell with a few general provisos. First because in some case you maybe deleting a lot of items (eg I had to remove over 100000) using the batching features of EWS is highly desirable which will reduce the number of requests you need to make to the server and make the script run in some sort of reasonable time.

To use batching with the EWS Managed API you need to make use of generictypes which presents a little bit of challenge in Powershell v1. To get around this you need to use something like this is PS v1 to great a generic List type of EWS Items.

$Itemids = [activator]::createinstance(([type]'System.Collections.Generic.List`1').makegenerictype([Microsoft.Exchange.WebServices.Data.ItemId]))

Other important parts of this script is that with the Delete Method in exchange you can move items to the recycle bin, soft delete them or Hard delete them which method you use on a item will affect it retention and recoverability of that item. In this script because this is a example im using SoftDelete which give some chance of redemption in production once tested you probably want to switch to HardDelete.

[Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete

Care does need to be taken because when you hard delete an item it means generally you won’t be able to recover it except from backup.

The script uses the following searchfilter to limit the items returned to NDR’s

$Sfir = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "REPORT.IPM.Note.NDR")

To run the script itself it takes the name of the mailbox you want to run it against as a cmdline parameter so to run it against the admin account it would take something like

./Ndrhunt.ps1 administrator

Warning this script has had no real testing and because it deletes email I advise you do your own testing first.

I've put a download of this script here the script itself look like


$MailboxName = $args[0]

function RepeartSearch{
$frFolderResult = $InboxFolder.FindItems($Sfir,$view)
$Itemids = [activator]::createinstance(([type]'System.Collections.Generic.List`1').makegenerictype([Microsoft.Exchange.WebServices.Data.ItemId]))
foreach($ndr in $frFolderResult.items){
$Itemids.add($ndr.Id)
}
if ($frFolderResult.Items.Count -ne 0){
$Result = $service.DeleteItems($Itemids,[Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete,[Microsoft.Exchange.WebServices.Data.SendCancellationsMode]::SendToNone,[Microsoft.Exchange.WebServices.Data.AffectedTaskOccurrence]::AllOccurrences)
[INT]$Rcount = 0
foreach ($res in $Result){
if ($res.Result -eq [Microsoft.Exchange.WebServices.Data.ServiceResult]::Success){
$Rcount++
}
}
$Rcount.ToString() + " Items Deleted"
if ($frFolderResult.Items.Count -eq 1000) {
RepeartSearch
}
}
else{
"No Items to delete"
}

}

$dllpath = "C:\Program Files\Microsoft\Exchange\Web Services\1.0\Microsoft.Exchange.WebServices.dll"
[void][Reflection.Assembly]::LoadFile($dllpath)
$service = New-Object Microsoft.Exchange.WebServices.Data.ExchangeService([Microsoft.Exchange.WebServices.Data.ExchangeVersion]::Exchange2007_SP1)

$windowsIdentity = [System.Security.Principal.WindowsIdentity]::GetCurrent()
$sidbind = "LDAP://<SID=" + $windowsIdentity.user.Value.ToString() + ">"
$aceuser = [ADSI]$sidbind

$service.AutodiscoverUrl($aceuser.mail.ToString())

$folderid = new-object Microsoft.Exchange.WebServices.Data.FolderId([Microsoft.Exchange.WebServices.Data.WellKnownFolderName]::Inbox,$MailboxName)
$InboxFolder = [Microsoft.Exchange.WebServices.Data.Folder]::Bind($service,$folderid)
$Sfir = new-object Microsoft.Exchange.WebServices.Data.SearchFilter+IsEqualTo([Microsoft.Exchange.WebServices.Data.ItemSchema]::ItemClass, "REPORT.IPM.Note.NDR")
$view = new-object Microsoft.Exchange.WebServices.Data.ItemView(1000)
$frFolderResult = $InboxFolder.FindItems($Sfir,$view)

$Itemids = [activator]::createinstance(([type]'System.Collections.Generic.List`1').makegenerictype([Microsoft.Exchange.WebServices.Data.ItemId]))
foreach($ndr in $frFolderResult.items){
$Itemids.add($ndr.Id)
}
if ($frFolderResult.Items.Count -ne 0){
$Result = $service.DeleteItems($Itemids,[Microsoft.Exchange.WebServices.Data.DeleteMode]::SoftDelete,[Microsoft.Exchange.WebServices.Data.SendCancellationsMode]::SendToNone,[Microsoft.Exchange.WebServices.Data.AffectedTaskOccurrence]::AllOccurrences)
[INT]$Rcount = 0
foreach ($res in $Result){
if ($res.Result -eq [Microsoft.Exchange.WebServices.Data.ServiceResult]::Success){
$Rcount++
}
}
$Rcount.ToString() + " Items Deleted"
if ($frFolderResult.Items.Count -eq 1000) {
RepeartSearch
}
}
else{
"No Items to delete"
}

Wednesday, March 10, 2010

Mailbox Size Gui - Exchange 2010 Remote Powershell version

One of the most popular scripts I've posted over the past few years has been the mailbox size gui for Exchange 2007 which evolved over a few different versions. While this is really only scratching the surface of the kind of cool things you can do with this information time and life hasn't really allowed me to make it better. But what i have managed to do is to port it to work with Exchange 2010 using remote powershell from a Windows 7 workstation.

A few challenges that needed to be solved to do this was first a front-end winform that allowed you to select the Exchange server you want to remote the powershell session to. Then some simple code to establish the remote PS Session which look like this

[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")

$form1 = new-object System.Windows.Forms.form
$form1.Text = "Exchange 2010 Remote PS Select"
$form1.size = new-object System.Drawing.Size(400,200)
$ServerName = ""
$conuri = ""
# Add Server DropLable
$snServerNamelableBox1 = new-object System.Windows.Forms.Label
$snServerNamelableBox1.Location = new-object System.Drawing.Size(10,20)
$snServerNamelableBox1.size = new-object System.Drawing.Size(120,20)
$snServerNamelableBox1.Text = "Remote ServerName"
$form1.Controls.Add($snServerNamelableBox1)

$exButton4 = new-object System.Windows.Forms.Button
$exButton4.Location = new-object System.Drawing.Size(10,80)
$exButton4.Size = new-object System.Drawing.Size(125,20)
$exButton4.Text = "Connect"
$exButton4.Add_Click({
$conuri = "http://" + $ServerName + "/PowerShell/"
$form1.close()
})
$form1.Controls.Add($exButton4)


# Add Server Drop Down
$snServerNameDrop1 = new-object System.Windows.Forms.ComboBox
$snServerNameDrop1.Location = new-object System.Drawing.Size(150,20)
$snServerNameDrop1.Size = new-object System.Drawing.Size(160,30)
$snServerNameDrop1.Add_SelectedValueChanged({$ServerName = $snServerNameDrop1.SelectedItem.ToString()})

$form1.Controls.Add($snServerNameDrop1)

$root = [ADSI]'LDAP://RootDSE'
$cfConfigRootpath = "LDAP://" + $root.ConfigurationNamingContext.tostring()
$configRoot = [ADSI]$cfConfigRootpath
$searcher = new-object System.DirectoryServices.DirectorySearcher($configRoot)
$searcher.Filter = '(objectCategory=msExchExchangeServer)'
[VOID]$searcher.PropertiesToLoad.Add("cn")
$searchres = $searcher.FindAll()
foreach ($res in $searchres){
$srvOjb = $res.Properties
$snServerNameDrop1.Items.Add($srvOjb.cn[0])
}

$form1.autoscroll = $true
$form1.Add_Shown({$form1.Activate()})
$form1.ShowDialog()

The next challenge was to do with the way the objects are sent and recieved between remote ps session which is explained in detail here. What this menas is that the Byte Quantified Size type isn't availble so what you recieve at the remote end is the string format version of the data structure which needs a simple parse to retrieve the byte information. With this

function CovertBitValue($String){
$numItempattern = '(?=\().*(?=bytes)'
$matchedItemsNumber = [regex]::matches($String, $numItempattern)
$Mb = [INT64]$matchedItemsNumber[0].Value.Replace("(","").Replace(",","")
return [math]::round($Mb/1048576,0)
}

This still needs a little more testing but seems to work okay I've put a download of the new script here.