Skip to main content

Reporting on forwarding rules in Mailboxes and Public Folders via a script

Reporting on rules in mailboxes and public folders can get a little challenging for the humble sysadmin. Because most the time the setting of these rules is out of your control knowing where some rules are forwarding can be a little scary (and in some cases can be against company policy or breach privacy laws). There are a few ways to manipulate rules one of the most often used is the rule.dll which can be used to create and enumerate rules while this is useful it still only offers you the hex value of the binary action property which contains the list of the recipient addresses for a forwarding rule. An active rule in a mailbox or public folders is a special message in a mailbox of type IPM.Rule.Message. In CDO 1.2 you can access these messages by using the hidden messages collection on a folder. If a rule is a forwarding rule then the email address’s the rule is forwarding to gets stored in the PR_RuleMsgActions (0x65EF0102) Mapi Property on that IPM.Rule.Message. Unfortunately this property is a binary property whose format is undocumented. Reverse engineering a complete decode for this property is a little hard and time consuming so what I did was just concentrate on matching the patterns within the binary property (its kind of like doing a jigsaw in the dark) but armed with my trusty ASCII chart I came up with some formulas that can separate out the text address’s from the rest of the information that is stored in the property and produce some meaning results (well it works for me anyway).

I’ve created two versions of this script the first loops though all the mailboxes on a server and looks at rules in the inbox of each mailbox. The second script loops though all the public folders on a server and reports on any forwarding rules in those public folders. The results are output to the screen and also a CSV file is created on the c: drive with the results.

The flow of the mailbox script is it takes in the name of the server as a command line parameter and then does a query of active directory for all the visible mailboxes on this server. Its then opens all the mailboxes and checks the hidden collection for any IPM.Rule.Message rule messages and then checks the PR_RuleMsgActions property on any rule messages it finds. If any address objects are found these are output to the command line and also stored in an array so they can be written to a CSV file at the end of the iteration. Once all rules have been checked for a mailbox the result is written in to a CSV file and it moves on to the next mailbox. The public folders script works similarly except instead of querying for mailboxes via Active Directory it uses CDO to loop though the folders collection and any subfolder therein.

To run the mailbox script you need to add the name of the server you want it to run against as a command-line parameter eg cscript mbxruleloop.vbs servername .With the public folders script you need to configure the servername and the name of mailbox on the server you want to report against (this is so the script can logon to the server the actually mailbox content isn’t accessed).

I’ve posted a downloadable copy of the script here the Mailbox script looks like

servername = wscript.arguments(0)
PR_URL_NAME = &H6707001E
Set fso = CreateObject("Scripting.FileSystemObject")
set wfile = fso.opentextfile("c:\mbxforwardingRules.csv",2,true)
set conn = createobject("ADODB.Connection")
set com = createobject("ADODB.Command")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strNameingContext = iAdRootDSE.Get("configurationNamingContext")
strDefaultNamingContext = iAdRootDSE.Get("defaultNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
svcQuery = "<LDAP://" & strNameingContext & ">;(&(objectCategory=msExchExchangeServer)(cn="
& Servername & "));cn,name,legacyExchangeDN;subtree"
Com.ActiveConnection = Conn
Com.CommandText = svcQuery
Set Rs = Com.Execute
while not rs.eof
GALQueryFilter = "(&(&(&(& (mailnickname=*)(!msExchHideFromAddressLists=TRUE)(|
(&(objectCategory=person) (objectClass=user)(msExchHomeServerName=" &
rs.fields("legacyExchangeDN") & ")) )))))"
strQuery = "<LDAP://" & strDefaultNamingContext & ">;" & GALQueryFilter & ";distinguishedName,mailnickname;subtree"
com.Properties("Page Size") = 100
Com.CommandText = strQuery
Set Rs1 = Com.Execute
while not Rs1.eof
call procmailboxes(servername,rs1.fields("mailnickname"))
wscript.echo rs1.fields("mailnickname")
set fso = nothing
set conn = nothing
set com = nothing
wscript.echo "Done"

Sub procmailboxes(servername,mailboxname)

set objSession = CreateObject("MAPI.Session")
objSession.Logon "","",false,true,true,true,servername & vbLF & mailboxname
Set objInfoStores = objSession.InfoStores
set objInfoStore = objSession.GetInfoStore
set Inbox = objSession.Inbox
if inbox.fields.item(PR_HAS_RULES) = true then
Set objMessages = inbox.HiddenMessages
for Each objMessage in objMessages
if objMessage.type = "IPM.Rule.Message" then
call procrule(objMessage,mailboxname,inbox.fields.item(PR_URL_NAME).value)
end if
end if

end sub

sub procrule(objmessage,MailboxName,folderpath)
frule = false
splitarry = split(hextotext(objmessage.fields.item(&H65EF0102)),chr(132),-1,1)
if ubound(splitarry) <> 0 then
wscript.echo "Mailbox Name :" & MailboxName
wscript.echo "Folder Path :" & folderpath
wscript.echo "Rule Created By : " & objmessage.fields.item(PR_CREATOR).value
mbname = MailboxName
fpath = folderpath
creator = objmessage.fields.item(PR_CREATOR).value
frule = true
end if
tfirst = 0
addcount = 1
for i = 0 to ubound(splitarry)
addrrsplit = split(splitarry(i),chr(176),-1,1)
for j = 0 to ubound(addrrsplit)
addrcontsep = chr(3) & "0"
if instr(addrrsplit(j),addrcontsep) then
if tfirst = 1 then addcount = addcount + 1
wscript.echo "Address Object :" & addcount
redim Preserve resarray(1,1,1,1,1,addcount)
resarray(1,0,0,0,0,addcount) = mbname
resarray(1,1,0,0,0,addcount) = fpath
resarray(1,1,1,0,0,addcount) = creator
if instr(addrrsplit(j),"0/o=") then
resarray(1,1,1,1,0,addcount) = mid(addrrsplit(j),(instr(addrrsplit(j),"0/o=")+1),len(addrrsplit(j)))
WScript.echo "ExchangeDN :" & mid(addrrsplit(j), (instr(addrrsplit(j),"0/o=")+1),len(addrrsplit(j)))
WScript.echo "Address :" & mid(addrrsplit(j),3, len(addrrsplit(j)))
resarray(1,1,1,1,0,addcount) = mid(addrrsplit(j),3,len(addrrsplit(j)))
end if
tfirst = 1
end if
smtpsep = Chr(254) & "9"
if instr(addrrsplit(j),smtpsep) then
slen = instr(addrrsplit(j),smtpsep) + 2
elen = instr(addrrsplit(j),chr(3))
Wscript.echo "SMTP Forwarding Address : " & mid(addrrsplit(j),slen,(elen-slen))
resarray(1,1,1,1,1,addcount) = mid(addrrsplit(j),slen,(elen-slen))
end if
if frule = true then
for r = 1 to ubound(resarray,6)
wfile.writeline(resarray(1,0,0,0,0,r) & "," & resarray(1,1,0,0,0,r) & "," &
resarray(1,1,1,0,0,r) & "," & resarray(1,1,1,1,0,r) & "," &
end if

end sub

Function hextotext(binprop)
arrnum = len(binprop)/2
redim aout(arrnum)
slen = 1
for i = 1 to arrnum
if CLng("&H" & mid(binprop,slen,2)) <> 0 then
aOut(i) = chr(CLng("&H" & mid(binprop,slen,2)))
end if
slen = slen+2
hextotext = join(aOUt,"")
end function

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 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 '

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.