Thursday, October 13, 2005

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_HAS_RULES = &H663A000B
PR_URL_NAME = &H6707001E
PR_CREATOR = &H3FF8001E
Set fso = CreateObject("Scripting.FileSystemObject")
set wfile = fso.opentextfile("c:\mbxforwardingRules.csv",2,true)
wfile.writeline("Mailbox,FolderPath,Creator,AdressObject,SMTPForwdingAddress")
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")
rs1.movenext
wend
rs.movenext
wend
rs.close
wfile.close
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
next
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
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
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)))
else
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
next
next
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) & "," &
resarray(1,1,1,1,1,r))
next
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)))
mid(binprop,slen,2)))
end if
slen = slen+2
next
hextotext = join(aOUt,"")
end function
 

45 comments:

Briam said...

Love your stuff. Have used a a bunch of your scripts! I was testing this one out, and I get the following after it runs through a few mailboxes:

C:\temp\mbxruleloop.vbs(98, 4) Microsoft VBScript runtime error: Invalid procedure call or argument: 'mid'

Any thoughts? I am running this with an account that has full Ex perms (Plus)

Glen said...

That doesn't look like a permission problem it looks like the script is comming across some data it doesn't know how to deal with. There are a few things you can do to try and fix this the first is you could put on error resume next at the top of the script which will make it just ignore this error (it could be just the one message that's causing the problem). The other thing you could do is try to work out why the error is happening if you do something like this before line 98 you should see the line that is cause the scirpt to fail

on error resume next
Wscript.echo "SMTP Forwarding Address : " & mid(addrrsplit(j),slen,(elen-slen))
if err.number <> 0 then
wscript.echo addrrsplit(j)
end if
on error goto 0

Anonymous said...

I have problem with creating a rule on exchange server throught vbs for all accounts. The rule shoud to move all incoming email with special line on message header to junk messages folder.
For example if message header contains X-Spam: Yes then move to folder... Can you help me, or mabey you've got some kind of issue.
Best regards
saber
email: saber (at) saber.pl

Glen said...

Have a read of http://gsexdev.blogspot.com/2006/11/creating-server-side-rule-to-move.html
This code could be adapted to do what you want also. To Create a rule for every mailbox you would need to use an account that has rights to all mailboxes. By default no account has these rights and if you use an administrative account these accounts are specifically denied access to all mailbox other then their own. To give an account the rights it needs have a read of http://www.petri.co.il/grant_full_mailbox_rights_on_exchange_2000_2003.htm

Cheers
Glen

Anonymous said...

Getting back to Briam's post, the problem is that in some cases the value of "elen" at line 98 is less than the value of slen, which is resulting in a negative third argument to mid, which it can't handle. (in case someone's changed the code that is this line Wscript.echo "SMPTPForwarding Address :" &mid(addrrsplit(j),slen,(elen-slen))

Anonymous said...

When I try to use it, logged in as full administrator, it returns a CDO error on line 45: Information store could not be opened MAPI_E_LOGON_FAILED 80040111

Glen said...

Yes Administrative Accounts by default are denied access to every other mailbox except their own. Have a read of http://support.microsoft.com/?kbid=262054 for workarounds

Anonymous said...

That's correct, it works for a user with allow send as and receive as. Thank you for the quick answer.

euricelia said...

Although I am using the script with an account that can actually execute ExMerge, which makes me assume the permissions are correct, I still keep getting the error below:
(46, 1) Collaboration Data Objects: The inform
ation store could not be opened. [MAPI 1.0 - [MAPI_E_LOGON_FAILED(80040111)]]
Any ideas? Thank you

Glen said...

It could just be one account thats causing it to fail eg something thats been disabled etc. What i would try is putting a

On error resume next

as the first line of the script it should then ignore any errors it has opening mailboxes and see if you can get any output

euricelia said...

I believe the problem is that part of the users is not in the GAL. They are part of another address list. Is there any way to make this work for those that are not in the GAL?

Glen said...

You could feed the names into the sub manually otherwise you need to try and tweek the ADSI LDAP query to include those users

Cheers
Glen

Mark said...

Hi Glen,

This is just what I've been looking for!

I have a problem when I run the script, getting the following error:

C:\Temp\rules\mbxruleloop.vbs(104, 2) Microsoft VBScript runtime error: Type mismatch: 'ubound'

Line 104 is:
for r = 1 to ubound(resarray,6)

Is it possible that resarray may not actually be an array (ie is it guaranteed to always be an array, and not a text string if only 1 rule exists)?

Glen said...

It could be a parse error one thing to try would be to put a

on error resume next

as the first line and just see if its one rule thats causing the problem. It could be a rule type that i hadn't thought of the script should work with just one forwarding rule.

Anonymous said...

I get error C:\mxrules\mbxruleloop.vbs(105, 2) Microsoft VBScript runtime error: Type mismatch: 'ubound'
on the first mailbox

Jeremy said...

For those receiving the following error:
(46, 1) Collaboration Data Objects: The inform
ation store could not be opened. [MAPI 1.0 - [MAPI_E_LOGON_FAILED(80040111)]]

I had to ensure that permissions allowed access and that the account had an active & associated "Mailbox".

Hope that helps.

J.Senter said...

When I run this I get the following error, any ideas?

mbxrulelop.vbs(42, 1) Microsoft VBScript runtime error: ActiveX co
mponent can't create object: 'MAPI.Session'

Glen said...

This script requires CDO 1.2 if your using Outlook 2007 then it wont be their. So you need to run it on a machine that has an older version of Outlook or install the CDO standalone client http://www.microsoft.com/downloads/details.aspx?FamilyID=2714320d-c997-4de1-986f-24f081725d36&DisplayLang=en

Cheers
Glen

Anonymous said...

Great scripts. How can the public folder rules version be modified to return all public folders which have have "Reply with" checked.

Jason said...

Will this work on exchange 2007 or is there an easier way?
thanks

Glen said...

Yes it should work okay on 2007,The Outlook 2007 OOM now supports rules so potentially you could use this interface to write something that did the same thing. whether that easier ??

Cheers
Glen

Anonymous said...

I running this and it seems to stay on one account, how long should it take per account?

Glen said...

I've been talking about this script with someone else over the past weeks and i've got an updated version because there was some problems with that original version in that it just read the hidden rule object in folder associated contents and not the Mapi rules table itself. It was also a very crude parser then seemed to error on different objects. To fix this i came up with a version that used redemption instead you can get a copy from http://www.dimastr.com/redemption/download.htm the advantage of this is this actually can read the Rules table in a mailbox so there's no need for the unreliable parser. Unfortunately for this particular guy and i've had a few other people report this sometime is that this would work but after about 32 mailboxes the script would stop because of the Open Mapi Session limit. I couldn't reproduce this and the code looked good in that it should have released the Mapi session when logoff method was called. To work around this problem i created a two script method the premise being that all the mapi code was in one script and the mapi session would get destroyed when the script finished running. I got a mail this morning from this guy and he said it worked okay. I've posted this two script example on http://msgdev.mvps.org/rdombxrules.zip if your interested in the one script its still their as well http://msgdev.mvps.org/rdombxrulesold.zip.

Phil said...

Quick question that I am sure you have the answer to. I see above in the posts there isnt a way to do this, aside from giving someone full mailbox rights to everyone that you are trying to change...but, here is what I am trying to accomplish.

I need to add root access folder visible, calendar access author, and contact access reviewer to one delegate for a whole distribution group. THe script I created works fine all in all, aside from the fact that only the profile that I am running this against actually changes. Is it possible to do what I am trying to do without adding one user that has full mailbox access? Anyway a domain or admin account can do this?

Glen said...

No you must have an account that has been granted rights on all mailboxes see http://www.petri.co.il/grant_full_mailbox_rights_on_exchange_2000_2003.htm

Cheers
Glen

Phil Thompson said...

Hi Glen,
thanks for your tips last week. I am still having trouble with changing everyone's calendars with my code. First, I did create a new user, non-admin, who has full rights to all mailboxes, but when I run the script, it ONLY changes its own mailbox files, but none of the other users. i have tried it in two ways, both typing in one users mailbox name into my script, and also via a group. Either way, again, it only changes the one user's mailbox. I am obviously missing something, but I cant think of what it could be.

Glen said...

Have you tested whether that user can logon to other people mailboxes using either Outlook or OWA. Without seeing your code it hard to say what your doing wrong.

Cheers
Glen

Phil Thompson said...

Thanks Glen,
Yes, I can login via OWA to another users calendar without any issues. i would be happy to send my code to you for you to take a look at. My email is philip.thompson at gmail.

Thanks.

Phil

j75 said...

Hi Glen,

For me, only the first original script is an option, since I've been not given a nod to install redemption SW in production. The script works well against Exchange 2007. However, only rules etup in Outlook thick client are visible to the script.. If there's a forwarding rule setup in OWA2007, it becomes invisible for the script. Even worse, it actually "hides" all the other forwarding rules, no matter how they were setup.. As soon as I open the rules in Outlook thick client, and literally do nothing else but pressing OK button, all fwding rules become visible to the script again.. Any idea how to deal with this issue, please? Thank you.
Joz

Glen said...

If this is happening to rules i wouldn't suggest using this approach the libraries its using are quite old it shouldn't be causing any issue because its only reading objects although it sounds like maybe there's a bug somewhere. the RDO method is reading the rules table which is a much better approach.

Cheers
Glen

Anonymous said...

Hi Glen,
Nice script. I am using the script in our environment and it runs successfully, but it doesnt return any details except for header. I can confirm that i have created two demo users with mailboxes and rules created. But the script doesnt find them.
Can you please advise?
Thanks in advance

Glen said...

I would suggest having a read through the other comments and looking at the RDO version I've linked.

Cheers
Glen

Anonymous said...

Thanks for your reply.

I have already used the RDO version but still it doesnt work. I have debugged the script and found that LDAP query is not working when i pass the AD servername. But as soon as i remove the filter (cn=& servername &) then it return the exchange names. But then it returns all the instances. I have tried to filter through name but still it doesnt work. Can you please advise?

I have also found that CDO 1.2.1 doesnt work for 64 bits operating system. Do you have any alternate script for 64 bits os?

Thanks in advance

Glen said...

You need to pass the Netbios name of the Exchange server if you pass the FQDN that wont work (you can confirm this yourself by looking in AdsiEdit at the particular name it querying) eg check the CN property on that server object.

On a 64bit os just start a 32 bit shell http://www.tipandtrick.net/2008/how-to-open-and-run-32-bit-command-prompt-in-64-bit-x64-windows/

Cheers
Glen

Anonymous said...

Hi there

Getting the following error on Exchange 2003 when running your script:
C:\Utils\mbxrulelookup\mbxruleloop.vbs(99, 4) Microsoft VBScript runtime error:
Type mismatch: 'resarray'

Please help. This is the complete output:
C:\Utils\mbxrulelookup>cscript mbxruleloop.vbs EXC2003SRv
Microsoft (R) Windows Script Host Version 5.6
Copyright (C) Microsoft Corporation 1996-2001. All rights reserved.

edmoat
edmuat
edmtrain

Mailbox Name :edmunit
Folder Path :/Inbox
Rule Created By : EDM UNIT
SMTP Forwarding Address : Nick.Wilson@123.com☻☺♂0FEX:/O=123/OU=FIRST ADMINISTR
ATIVE GROUP/CN=RECIPIENTS/CN=NICK.WILSON
C:\Utils\mbxrulelookup\mbxruleloop.vbs(99, 4) Microsoft VBScript runtime error:
Type mismatch: 'resarray'

Anonymous said...

Hi Glen,
perfect script. Thank you very much. One question. Is it possible to change the scope on an other exchange-subdomain. We have one root-domain and two sub-domains. unfortunately the script dosn't search in the sub-domain. All mailboxes with forwarding rules in the root-domain be found. Do you have an idea? Thanks again - Mario

Chris B said...

Any more information on this? I have tried both script methods and they both crash cscript.

Glen said...

Try http://gsexdev.blogspot.com/2011/03/display-delegate-forward-rules-and.html if your using 2010

Cheers
Glen

Kristofer said...

I tried the script and first noticed I didn't have the necessary rights on the server. After I fixed the rights, the script keeps failing with the error message: chkdelv4.vbs(49, 2) Microsoft VBScript runtime error: ActiveX component can't create object: 'MSExchange.Rules'

The machine has Outlook 2003 installed.

Glen said...

That means you don't have the Rule.dll installed which im not sure is still available http://support.microsoft.com/kb/251125. My suggestion is you read through the other comments where I've linked a Redemption version that should work better then this script.

Cheers
Glen

Kristofer said...

I tried the Redemption version and I had the same problem as Chris B. Both of the script versions crashes on two different machines. If Data Execution Prevention is enabled, it shuts the script down.
I can't use the Powershell script you suggested to him, because we're using Exchange Server 2007.

Philip Self said...

This probably long dead now but ... 404 error

Anonymous said...

Apologies to revive such an old thread, but I wanted to ask a question regarding the script;
on my initial attempt at running, I see an error returned almost immediately, relating to line #16. The error is as follows:

C:\mbxruleloop.vbs(16, 1) Microsoft VBScript compilation error: Expected statement

I am running the script as described:

cscript mbxruleloop.vbs MyServerName

The error appears to relate to the following line in the script:

& Servername & "));cn,name,legacyExchangeDN;subtree"

Any and all help would be much appreciated.

Thank you in advance...

Anonymous said...

A formatting error was causing this, so please disregard. Currently having some fun with the "ActiveX component can’t create object (MAPI.Session)" error and as I understand it, CDO 1.21 is x86 only, so attempting to locate a suitable node to run this from.

Anonymous said...

Currently troubleshooting the following error:

mbxruleloop.vbs(43, 1) Collaboration Data Objects: You do not have permission to log on. [Microsoft Exchange Server Information Store - [MAPI_E_FAILONEPROVIDER(8004011D)]]

Any pointers? The account I'm logged into Windows has both administrative access to Exchange and a valid Mailbox.

Thank you...