Friday, May 26, 2006

Power-Shelling the Message Tracking logs on Exchange 2000/2003

If you’ve ever had to write any scripts that query the message tracking logs though WMI you may have come across the issue that WQL cant handle doing a Where clause on an array. Because the Recipient address’s on an email are returned as an array when you want to use this class to make a query that only shows mail that is going to one address it can be a little cumbersome. With Powershell although you are still stuck not being able to filter via recipient address in a WMI query what you can do now is pipe that result to the where-object cmdlet where you can then filter the result to one particular recipient address.

If you combine this in a script what you can then do is query the tracking logs for the past x number of hours to show any email sent to a particular recipient. The reverse is also true you can query to see all the email sent from a particular address.

What I’ve done is put two scripts together that do this both scripts take 3 input parameters the first is the name of the server you want to query. The second is the number of hours to look back in the logs and the third is the email address to look at so to run the script you use a line such as c:\recvmail.ps1 servername 10 user@domain.com . This would look for any mail sent to user@domain.com on the server for the last 10 hours. The sent mail script works that same but shows messages that where sent from a particular email address The script requires that your running the Powershell RC but it should work in the old msh / monad beta’s as well.

I’ve put a downloadable copy of the script here

The Received email script looks like

param([String] $servername = $(throw "Please specify the Servername"), [int32] $timerange = $(throw "Please specify a Time Range in Hours"),[String] $emailaddress= $(throw "Please Specify the Email address you wish to use"))
$dtQueryDT = [DateTime]::UtcNow.AddHours(-$timerange)
$WmidtQueryDT = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime($dtQueryDT)

$WmiNamespace = "ROOT\MicrosoftExchangev2"
$filter = "entrytype = '1020' and OriginationTime >= '" + $WmidtQueryDT + "' or entrytype = '1028' and OriginationTime >= '" + $WmidtQueryDT + "'"
get-wmiobject -class Exchange_MessageTrackingEntry -Namespace $WmiNamespace -ComputerName $servername -filter $filter | where-object {$_.RecipientAddress -eq $emailaddress} | where-object {$_.SenderAddress -ne "<>"} | ft @{expression={[System.Management.ManagementDateTimeConverter]::ToDateTime($_.OriginationTime)}; width=25; label="Time Sent"},SenderAddress,Subject

The sent Email script looks like

param([String] $servername = $(throw "Please specify the Servername"), [int32] $timerange = $(throw "Please specify a Time Range in Hours"),[String] $emailaddress= $(throw "Please Specify the Email address you wish to use"))
$dtQueryDT = [DateTime]::UtcNow.AddHours(-$timerange)
$WmidtQueryDT = [System.Management.ManagementDateTimeConverter]::ToDmtfDateTime($dtQueryDT)
$WmiNamespace = "ROOT\MicrosoftExchangev2"
$filter = "entrytype = '1020' and OriginationTime >= '" + $WmidtQueryDT + "' and SenderAddress = '" + $emailaddress + "' or entrytype = '1028' and OriginationTime >= '" + $WmidtQueryDT + "' and SenderAddress = '" + $emailaddress + "'"
get-wmiobject -class Exchange_MessageTrackingEntry -Namespace $WmiNamespace -ComputerName $servername -filter $filter | ft @{expression={[System.Management.ManagementDateTimeConverter]::ToDateTime($_.OriginationTime)}; width=25; label="Time Sent"},@{expression={$_.RecipientCount};width=5;label="#Recp"},RecipientAddress,Subject

Wednesday, May 17, 2006

Company Instant Message RSS feed Notice Board LCS response Bot using communicator Web Access (Ajax)

Company announcement notice boards are something I’ve done a bit in the past usually these are web based the last one I did a while ago used a simple Exchange Event sink to create a simple web based notice board where information about company events could be posted to a mailbox and appear on the web page. They are also useful for posting things like network outages or as a change control list. With new technology comes new ways of doing things and seeing how I had the code for creating a LCS bot and a RSS feed it seemed natural to join them together and basically have a LCS bot that creates and RSS feed based on Instant message you send to it.

The bot part of this code work’s as per my pervious post the RSS feed part creates a simple RSS document using the MICROSOFT.XMLDOM object. Because you can’t specify a subject and body in IM there’s some code that looks for any carriage returns in the Instant message and if it finds a carriage return it takes the first section as the title for the new post. It then uses the rest of the message as the body of the post. There’s also a further bit of code that coverts any carriage returns in the post to html breaks. The RSS feed is also self managing so at the top of the script there is a variable where you can specify the maximum number of posts you want to have in the feed the script then handles removing any old posts as new ones are added.

To run this script you first need to configure the following four variables at the top of the script

SipURI = "user@domain.com"
Servername = "servername.domain.com"
userName = "domain\username"
Password = "password"

And then the following two variables need to be configured with the location you want the feed file save to and the maximum number of items you want in the feed

feedfilename = "E:\inetpub\wwwroot\LCSfeed.xml"
Maxitemnumber = 20

After you’ve configured the script all you need to do is start it from the command shell like

Cscript CBLcsrespbotv1.vbs

The script is very verbose and should return a lot of information back to the console while it’s running.

I’ve put a downloadable copy of the script here the script itself looks like

SipURI = "user@domain.com"
Servername = "servername.domain.com"
userName = "domain\username"
Password = "password"

feedfilename = "E:\inetpub\wwwroot\LCSfeed.xml"
Maxitemnumber = 20

set conn = createobject("ADODB.Connection")
set com = createobject("ADODB.Command")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
Com.ActiveConnection = Conn
strNameingContext = iAdRootDSE.Get("configurationNamingContext")
strDefaultNamingContext = iAdRootDSE.Get("defaultNamingContext")

set objdom = CreateObject("MICROSOFT.XMLDOM")
Set fso = CreateObject("Scripting.FileSystemObject")


if fso.FileExists(feedfilename) then
objdom.async="false"
objdom.load(feedfilename)
Set xnItemNodes = objdom.getElementsByTagName("item")
Set xnChannelNodes = objdom.getElementsByTagName("channel")
wscript.echo xnItemNodes.length
if xnItemNodes.length > Maxitemnumber then
for i = Maxitemnumber to xnItemNodes.length
set parentnode = xnItemNodes(i-1).parentnode
parentnode.removechild(xnItemNodes(i-1))
next
end if
set xnChannelNode = xnChannelNodes(0)
fptrack = 0
else
' ************ Create Root XML Elemements ************************
fptrack = 1
Set objField = objDom.createElement("rss")
Set objattID = objDom.createAttribute("version")
objattID.Text = "2.0"
objField.setAttributeNode objattID
objDom.appendChild objField
Set xnChannelNode = objDom.createElement("channel")
objfield.appendChild xnChannelNode
Set objField4 = objDom.createElement("title")
objfield4.text = "Company Instant Message Notice Board"
xnChannelNode.appendChild objField4
Set objField5 = objDom.createElement("description")
objfield5.text = "Company Instant Message Notice Board"
xnChannelNode.appendChild objField5
Set objField6 = objDom.createElement("language")
objfield6.text = "en-us"
xnChannelNode.appendChild objField6
Set objField7 = objDom.createElement("lastBuildDate")
objfield7.text = WeekdayName(weekday(now),3) & ", " & day(now()) & " " &
Monthname(month(now()),3) & " " & year(now()) & " " & formatdatetime(now(),4) &
":00 GMT"
xnChannelNode.appendChild objField7
Set objPI = objDom.createProcessingInstruction("xml", "version='1.0'")
objDom.insertBefore objPI, objDom.childNodes(0)
' ************ Create Root XML Elemements ************************
end if

set req = createobject("microsoft.xmlhttp")
req.Open "GET", "https://" & Servername & "/iwa/logon.html?uri=" & SipURI & "&signinas=1&language=en&epid=",
False, Username, Password
req.send
reqhedrarry = split(req.GetAllResponseHeaders(), vbCrLf,-1,1)
for c = lbound(reqhedrarry) to ubound(reqhedrarry)
if instr(lcase(reqhedrarry(c)),"set-cookie:") then reqsessionID =
right(reqhedrarry(c),len(reqhedrarry(c))-12)
next
wscript.echo reqsessionID
chk = left(reqsessionID,36)
updatestr = "https://" & Servername & "/cwa/AsyncDataChannel.ashx?AckID=0&Ck=" &
chk
req.Open "GET", updatestr, False, Username, Password
req.setRequestHeader "Cookie:", reqsessionID
req.send
latupdate = mid(req.responsetext,instr(req.responsetext,"latestUpdate=")+14,instr(instr(req.responsetext,"latestUpdate=")+14,req.responsetext,chr(34))-(instr(req.responsetext,"latestUpdate=")+14))

while i <> 1
updatestr = "https://" & Servername & "/cwa/AsyncDataChannel.ashx?AckID=" &
latupdate & "&Ck=" & chk
req.Open "GET", updatestr, False, Username, Password
req.setRequestHeader "Cookie:", reqsessionID
req.send
wscript.echo req.status
if instr(req.responsetext,"div id=""exception""") then i = 1
oldlat = latupdate
latupdate = mid(req.responsetext,instr(req.responsetext,"latestUpdate=")+14,instr(instr(req.responsetext,"latestUpdate=")+14,req.responsetext,chr(34))-(instr(req.responsetext,"latestUpdate=")+14))
wscript.echo req.responsetext
wscript.echo latupdate
if latupdate = "yTimeout" then latupdate = oldlat
if instr(req.responsetext,"message=""") then
Imid = mid(req.responsetext,instr(req.responsetext,"imId=""")+6,instr(instr(req.responsetext,"imId=""")+6,req.responsetext,chr(34))-(instr(req.responsetext,"imId=""")+6))
message = mid(req.responsetext,instr(req.responsetext,"message=""")+9,instr(instr(req.responsetext,"message=""")+9,req.responsetext,chr(34))-(instr(req.responsetext,"message=""")+9))
wscript.echo "************************Message Recieved****************************"
wscript.echo message
wscript.echo "************************Message
Ends********************************"
wscript.echo Imid
exist = 0
if instr(req.responsetext,"inviters=""") then
Invite =
mid(req.responsetext,instr(req.responsetext,"inviters=""")+10,instr(instr(req.responsetext,"inviters=""")+10,req.responsetext,chr(34))-(instr(req.responsetext,"inviters=""")+10))
else
exist = 1
elen =
instr((instr(instr(req.responsetext,"action=""receive"""),req.responsetext,"uri=""")+5),req.responsetext,chr(34))
-
(instr(instr(req.responsetext,"action=""receive"""),req.responsetext,"uri=""")+5)
Invite =
mid(req.responsetext,instr(instr(req.responsetext,"action=""receive"""),req.responsetext,"uri=""")+5,elen)
end if
SIPQueryFilter = "(&(objectCategory=person)(msRTCSIP-PrimaryUserAddress=" &
Invite & "))"
strQuery1 = "<LDAP://" & strDefaultNamingContext & ">;" & SIPQueryFilter &
";DisplayName;subtree"
com.Properties("Page Size") = 100
Com.CommandText = strQuery1
Set Rs1 = Com.Execute
if rs1.recordcount <> 0 then
FromDisplay = rs1.fields("DisplayName")
else
FromDisplay = replace(Invite,"sip:","")
end if
call CreateItem(message,FromDisplay,fptrack)
Set xnItemNodes = objdom.getElementsByTagName("item")
Set xnChannelNodes = objdom.getElementsByTagName("channel")
wscript.echo xnItemNodes.length
if xnItemNodes.length > Maxitemnumber then
for i = Maxitemnumber to xnItemNodes.length
set parentnode = xnItemNodes(i-1).parentnode
parentnode.removechild(xnItemNodes(i-1))
next
end if
set xnChannelNode = xnChannelNodes(0)
fptrack = 0
objdom.save(feedfilename)
SendMessage("Thanks for your message it has been added to the board")
message = ""
Invite = ""
end if
wend


function SendMessage(message)

' ---Send Message---
Sendmsgcmd = "https://" & Servername & "/cwa/MainCommandHandler.ashx?Ck=" & chk
Messagestr = "cmdPkg=1,LcwAcceptImRequest," & Imid
req.open "POST", Sendmsgcmd, False, Username ,password
req.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
req.setRequestHeader "Cookie:", reqsessionID
req.send Messagestr
wscript.echo req.status
Sendmsgcmd = "https://" & Servername & "/cwa/MainCommandHandler.ashx?Ck=" & chk
Messagestr = "cmdPkg=2,LcwSendMessageRequest," & Imid & "," & Message &
",X-MMS-IM-Format: FN=Arial%253B EF=%253B CO=000000%253B CS=1%253B PF=00"
req.open "POST", Sendmsgcmd, False, Username ,password
req.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
req.setRequestHeader "Cookie:", reqsessionID
req.send Messagestr
wscript.echo req.status

end function

Sub CreateItem(PostSubject,PostFrom,Fp)
PostBody = ""
if instr(PostSubject,chr(10)) then
PostBody =
mid(PostSubject,instr(PostSubject,chr(10)),len(postsubject)-instr(PostSubject,chr(10)))
postbody = replace(postbody,chr(10),"<br>")
PostSubject = left(PostSubject,instr(PostSubject,chr(10)))
end if
rndval = Int((20000000000 * Rnd) + 1)
rval = day(now) & month(now) & year(now) & hour(now) & minute(now) & rndval
Set objField2 = objDom.createElement("item")
if fp = 1 then
xnChannelNode.appendChild objField2
else
xnChannelNode.insertbefore objField2, xnItemNodes(0)
end if
Set objField8 = objDom.createElement("guid")
Set objattID8 = objDom.createAttribute("isPermaLink")
objattID8.Text = "false"
objField8.setAttributeNode objattID8
objfield8.text = rval
objfield2.appendChild objField8
Set objField9 = objDom.createElement("title")
objfield9.text = PostSubject
objfield2.appendChild objField9
if PostBody <> "" then
Set objField11 = objDom.createElement("description")
objfield11.text = PostBody
objfield2.appendChild objField11
end if
Set xnChannelNode0 = objDom.createElement("author")
xnChannelNode0.text = PostFrom
objfield2.appendChild xnChannelNode0
Set xnChannelNode1 = objDom.createElement("pubDate")
xnChannelNode1.text = WeekdayName(weekday(now),3) & ", " & day(now()) & " " &
Monthname(month(now()),3) & " " & year(now()) & " " & formatdatetime(now(),4) &
":00 GMT"
objfield2.appendChild xnChannelNode1
set objfield2 = nothing
set objfield8 = nothing
set objfield9 = nothing
set xnChannelNode0 = nothing
set xnChannelNode1 = nothing

End Sub

Wednesday, May 10, 2006

Change the Journal Recipient for an Exchange Store with CDOEXM via a Script

I’ve been asked the above question a few times by different people and although there is nothing in the Exchange SDK about this someone pointed me to an the following KB article that shows how to do this in C++. This being a little unfriendly for us mere mortals I put the following script together to hopefully make things a little easier. To reduce the need to go in to ADSI edit and get the DN name of the store object and the user object you want to switch journaling to I put some ADSI queries that will find the store in Active directory based on the stores friendly name (display name in ESM) and the another query that will find the user based on there logon name (samaccountname). The script to change the journal recipient is pretty basic it uses the iMailboxStoreDB interface to change the msExchMessageJournalRecipient Active directory property via the field’s property. Although you could probably do this directly via ADSI it’s probably advisable to stick to CDOEXM. The one thing to note about the msExchMessageJournalRecipient Active directory property as stated in this
“ This attributes are read and cached by Directory Service Access (DSAccess), which is the local directory cache on each Exchange server. DSAccess is updated every 15 minutes; therefore, any configuration change you make to these attributes takes no more than 15 minutes to update on the local Exchange computer (you must also take into account replication for multiple domains).”

To run the script you must pass in three commandline parameters the first parameter is the servername where the store is you want to run this against. The second parameter is the displyaname of the store in ESM eg for the default store it would be Mailbox Store (servername) if there are spaces in the store name you need to make sure you enclose the name is double quotes. The last commandline parameter required is the logonname of the account you want to be the journal recipient (make sure you use the samaccountname not a UPN). So to run the script to change the journal recipient on the default mailstore on a server to a useraccount jrnlaccount it would look like

Cscript chjrnrecpv1.vbs servername “Mailbox Store (Servername)” jrnlaccount

I put a downloadable copy of the script here the code itself looks like

Servername = wscript.arguments(0)
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 = ";(&(objectCategory=msExchExchangeServer)(cn=" & Servername & "));cn,name,distinguishedName;subtree"
Com.ActiveConnection = Conn
Com.CommandText = svcQuery
Set snrs = Com.Execute
mbQuery = ";(&(&(objectCategory=msExchPrivateMDB)(msExchOwningServer=" & snrs.fields("distinguishedName") & ")(cn=" & wscript.arguments(1) & ")));name,distinguishedName;subtree"
Com.ActiveConnection = Conn
Com.CommandText = mbQuery
Set Rs = Com.Execute
While Not Rs.EOF
exStoreDN = "LDAP://" & rs.fields("distinguishedName")
rs.movenext
Wend
if exStoreDN = "" then wscript.echo "No Store Found"
usrQuery = ";(mailnickname=" & wscript.arguments(2) & ");name,distinguishedName;subtree"
Com.ActiveConnection = Conn
Com.CommandText = usrQuery
Set RsUsr = Com.Execute
While Not RsUsr.EOF
jnJournalDN = RsUsr.fields("distinguishedName")
RsUsr.movenext
Wend
if jnJournalDN = "" then wscript.echo "No User Found"
if jnJournalDN <> "" and exStoreDN <> "" then
wscript.echo "Can configure"
set exExchangeStore = createobject("CDOEXM.MailboxStoreDB")
exExchangeStore.datasource.open exStoreDN,,3
wscript.echo "Current Journal Recipient set to " & exExchangeStore.fields("msExchMessageJournalRecipient")
wscript.echo
exExchangeStore.fields("msExchMessageJournalRecipient").value = jnJournalDN
exExchangeStore.fields.update
exExchangeStore.datasource.save
set exExchangeStore = nothing
wscript.echo "New Journal Recipient set to " & jnJournalDN
Else
wscript.echo
wscript.echo "one of the parameters passed in was not valid the script can't continue"
wscript.echo "use Syntax cscript chjrnrecpv1.vbs servername ""Mailbox Store (servername)"" mailboxalias"
end if

Wednesday, May 03, 2006

Finding and Removing Empty Distribution Lists/Groups via a script

Somebody asked about this one last week while there are some valid reasons for having empty distribution lists usually they are things that can stick around because no-one's quite sure if they should be deleted. Writing a script to find and delete empty distribution lists is not too hard although I have put a bunch of safeguards in this script to stop you deleting any groups that you may not want to. Note this script doesn’t differentiate between a distribution group and a security group it just looks for any groups that are mail enabled that have no members.

The script first does a search of AD for all mail enabled groups in active directory. It then connects to each group and starts going though its members. If there are more the 10 users in the group it stops counting. This wasn’t really a script to document the members in groups as this can get quite complicated when you consider nesting groups. If you’re after such a script Richard Muller has already written a great script to do this see http://www.rlmueller.net/. After a group is identified as empty the script will then ask if you wish to delete this group. This delete is irreversible so you need to make sure you don’t want to use this group and you have no security associations with it.

The script has two modes it can run in if you just run it with no command line parameters it will just display the mail enabled groups in Active Directory with the member counts (up to 10) for each group. Running the script with the remove switch eg cscript emptdist.vbs remove will run the script in remove mode which means it will prompt you to delete any groups that are found to have no members.

I’ve put a downloadable copy of this script here the script itself look like.


if wscript.arguments.length = 0 then
wscript.echo "Display Mode"
else
if lcase(wscript.arguments(0)) = "remove" then
mode = "remove"
wscript.echo "Remove Mode"
else
wscript.echo "Display Mode"
end if
end if
set conn = createobject("ADODB.Connection")
set com = createobject("ADODB.Command")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strDefaultNamingContext = iAdRootDSE.Get("defaultNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
GALQueryFilter = "(&(mailnickname=*)(|(objectCategory=group)))"
strQuery = "<LDAP://" & strDefaultNamingContext & ">;" & GALQueryFilter & ";distinguishedName,displayname,legacyExchangeDN,homemdb;subtree"
Com.ActiveConnection = Conn
Com.CommandText = strQuery
Set Rs = Com.Execute
wscript.echo "# Memebers GroupName"
wscript.echo
while not rs.eof
set objgroup = getobject("LDAP://" & replace(rs.fields("distinguishedName"),"/","\/"))

numcheck = 0
for each member in objgroup.members
numcheck = numcheck + 1
if numcheck = 10 then exit for
next
select case numcheck
case 0 wscript.echo "Empty" & " " & rs.fields("displayname")
if mode = "remove" then
contname = replace(objgroup.distinguishedName,"CN=" & objgroup.cn & ",","")
wscript.echo
wscript.echo "The Group " & rs.fields("displayname") & " in the " & contname & "
container is Empty"
WScript.StdOut.WriteLine "Do you wish to delete this List Press Y to Delete
(This is a irreversible operation)"
ans = WScript.StdIn.ReadLine
if lcase(ans) = "y" then
set objcont = getobject("LDAP://" & replace(contname,"/","\/"))
objcont.delete "group", "CN=" & replace(objgroup.cn,"/","\/")
objcont.setinfo
Wscript.echo "Deleted Group " & objgroup.displayname
else
wscript.echo "Skipping"
end if
wscript.echo
end if
case 10 wscript.echo "10+" & " " & rs.fields("displayname")
case else wscript.echo numcheck & " " & rs.fields("displayname")
end select
rs.movenext
wend