Thursday, July 26, 2007

Show Users last Message Sent and Received Times,Subject in a Form using Powershell against Exchange 2007 Message Tracking Logs

In the past I’ve written and shown many ways to use Message tracking Log data in Exchange 2000-2003 using the WMI MessageTrackingLog class. With Exchange 2007 the WMI class is now gone replaced with a new Exchange Management Shell Powershell cmdlet. Although losing the richness of WQL is a little bit of shame the new cmdlet is pretty funky especially the little status bar (that’s gold).

Message Tracking Logs can have many uses none more so then showing you current mailbox activity like who is actively sending and receiving mail in the last X number of minutes which may be important to you if you are working late at night on a server and you need to know who is active.

This is my first go at a messagetracking log script for 2007 and I must admit I’m lacking some good load data at the moment for Exchange 2007. What this script does is creates a winform with a few Date and Time controls and populates a Drop down box with the names of the Exchange servers within an Exchange organization using the get-ExchangeServer cmdlet. It then aggregates the message tracking logs results together to show in the time period scaned which users have been sending and receiving messages. How much time has lapsed since they last sent and received something and also what the subject of there last send and received message was.

Determine what is Internal vs. External email

When you are writing a Message Tracking Log script this is usually one of the big challenges for Exchange 2007 I took a slightly different approach by making use of another new EMS cmdlets called Get-AcceptedDomain. This cmdlet allows you to get a list of all the domains that your Exchange org is configured to receive email for which ergo with a bit of parsing becomes your list of internal domains with which you can classify email. For this script the accepted domains are added to a hashtable to allow for comparisons to be done in this script.

Working out the Time since the last message was sent and received.

For this the New-TimeSpan cmdlet from powershell is used. This is a pretty powerful little function it returns a timespan object based on the input of two dates you feed it. In this script I make use of the total minutes to show how much time has elapsed between now and when the users last received and sent an email by comparing the current time and that of the received (or sent) datetime of the last message.

This script doesn’t do any filtering on the type of message tracking log entry retrieved using the get-messagetrackinglog cmdlet and limits the total number of entries it will retrieve using the -ResultSize parameter to 10000 records. Once the script has filtered the entires into a number of hashtables the results are feed back into an ADO.NET datatable and then displayed back to the user in a DataGrid which gives you all the sorting richness etc. If you have included the subject in the Message tracking logs the script will also show the subject of the last sent and received email for each user during the tracking period selected.

This is only really scratching the surface of what you can do with Message tracking Logs in Exchange 2007. I’ve put a downloadable copy of this script here the script itself looks like.

[System.Reflection.Assembly]::LoadWithPartialName("System.Drawing")
[System.Reflection.Assembly]::LoadWithPartialName("System.windows.forms")
$DomainHash = @{ }
$Senders = @{ }
$Recipeints = @{ }
$RecipeintsSubject = @{ }
$SendersSubject = @{ }

function GetLogs(){
$dtQueryDT = New-Object System.DateTime $dpTimeFrom.value.year,$dpTimeFrom.value.month,$dpTimeFrom.value.day,$dpTimeFrom2.value.hour,$dpTimeFrom2.value.minute,$dpTimeFrom2.value.second
$dtQueryDTf = New-Object System.DateTime $dpTimeFrom1.value.year,$dpTimeFrom1.value.month,$dpTimeFrom1.value.day,$dpTimeFrom3.value.hour,$dpTimeFrom3.value.minute,$dpTimeFrom3.value.second
$ltTable.clear()
$Recipeints.clear()
$Senders.clear()
$DomainHash.clear()
$SendersSubject.clear()
$RecipeintsSubject.clear()
get-accepteddomain | ForEach-Object{
if ($_.DomainType -eq "Authoritative"){
$DomainHash.add($_.DomainName.SmtpDomain.ToString().ToLower(),1)
}

}
get-messagetrackinglog -Server $snServerNameDrop.SelectedItem.ToString() -Start $dtQueryDT -End $dtQueryDTf -ResultSize 10000 | ForEach-Object{
if ($_.EventId -eq "Send" -bor $_.EventId -eq "Receive"){
$saSndArray = $_.Sender.ToString().Split("@")
if ($saSndArray.length -gt 0){
if ($DomainHash.ContainsKey($saSndArray[1].ToLower())){
if ($Senders.ContainsKey($_.Sender.ToString().ToLower()) -eq $false){
$Senders.Add($_.Sender.ToString().ToLower(),$_.Timestamp.ToString())
$SendersSubject.Add($_.Sender.ToString().ToLower(),$_.MessageSubject.ToString())
}
else{
if ([DateTime]::Parse($Senders[$_.Sender.ToString().ToLower()]) -lt $_.Timestamp){
$Senders[$_.Sender.ToString().ToLower()] = $_.Timestamp.ToString()
$SendersSubject[$_.Sender.ToString().ToLower()] = $_.MessageSubject.ToString()
}
}
}
}
foreach ($recp in $_.recipients){
if ($recp -ne ""){
if ($Recipeints.ContainsKey($recp.ToLower()) -eq $false){
$Recipeints.Add($recp.ToLower(),$_.Timestamp.ToString())
$RecipeintsSubject.Add($recp.ToLower(),$_.MessageSubject.ToString())
}
else{
if ([DateTime]::Parse($Recipeints[$recp.ToLower()]) -lt $_.Timestamp){
$Recipeints[$recp.ToLower()] = $_.Timestamp.ToString()
$RecipeintsSubject[$recp.ToLower()] = $_.MessageSubject.ToString()
}
}
}
}


}}
foreach ($key in $Recipeints.keys){
$Recvtimespan = New-TimeSpan -start ($Recipeints[$key]) -end $(Get-Date)
$user = get-user $key
if ($user -ne $null){
if ($Senders.ContainsKey($key)){
$SentTimeSpan = New-TimeSpan -start ($Senders[$key]) -end $(Get-Date)
$ltTable.Rows.Add($user.displayName,$Senders[$key],[math]::round($SentTimeSpan.TotalMinutes,0),$Recipeints[$key],[math]::round($Recvtimespan.TotalMinutes),$RecipeintsSubject[$key],$SendersSubject[$key])}
else {$ltTable.Rows.Add($user.displayName,"n/a","n/a",$Recipeints[$key],[math]::round($Recvtimespan.TotalMinutes,0),$RecipeintsSubject[$key],"n/a")}
}}
foreach ($key in $Senders.keys){
$user = get-user $key
if ($user -ne $null){
if ($Recipeints.ContainsKey($key) -eq $false){
$SentTimeSpan = New-TimeSpan -start ($Senders[$key]) -end $(Get-Date)
$ltTable.Rows.Add($user.displayName,$Senders[$key],[math]::round($SentTimeSpan.TotalMinutes,0),"n/a","n/a","n/a",$SendersSubject[$key])

}}

}
$dgDataGrid.DataSource = $ltTable
}

$ltTable = New-Object System.Data.DataTable
$ltTable.TableName = "SentAndRecv"
$ltTable.Columns.Add("Mailbox")
$ltTable.Columns.Add("Last Mail Sent")
$ltTable.Columns.Add("Minutes since Last Mail Sent")
$ltTable.Columns.Add("Last Recieved Mail")
$ltTable.Columns.Add("Minutes since Last Mail Recieved")
$ltTable.Columns.Add("Subject of Last Mail Recieved")
$ltTable.Columns.Add("Subject of Last Mail Sent")
$form = new-object System.Windows.Forms.form
$form.Text = "Exchange Last Sent and Recieved Form"


# Add Search Button

$exButton = new-object System.Windows.Forms.Button
$exButton.Location = new-object System.Drawing.Size(270,20)
$exButton.Size = new-object System.Drawing.Size(85,20)
$exButton.Text = "Search"
$exButton.Add_Click({GetLogs})
$form.Controls.Add($exButton)

# Add Server DropLable
$snServerNamelableBox = new-object System.Windows.Forms.Label
$snServerNamelableBox.Location = new-object System.Drawing.Size(10,20)
$snServerNamelableBox.size = new-object System.Drawing.Size(100,20)
$snServerNamelableBox.Text = "ServerName"
$form.Controls.Add($snServerNamelableBox)

# Add Server Drop Down
$snServerNameDrop = new-object System.Windows.Forms.ComboBox
$snServerNameDrop.Location = new-object System.Drawing.Size(130,20)
$snServerNameDrop.Size = new-object System.Drawing.Size(130,30)
get-Exchangeserver | ForEach-Object{$snServerNameDrop.Items.Add($_.Name)}
# $snServerNameDrop.Add_SelectedValueChanged({GetLogs})
$form.Controls.Add($snServerNameDrop)
# Add DateTimePickers Button

$dpDatePickerFromlableBox = new-object System.Windows.Forms.Label
$dpDatePickerFromlableBox.Location = new-object System.Drawing.Size(10,50)
$dpDatePickerFromlableBox.size = new-object System.Drawing.Size(90,20)
$dpDatePickerFromlableBox.Text = "Logged Between"
$form.Controls.Add($dpDatePickerFromlableBox)

$dpTimeFrom = new-object System.Windows.Forms.DateTimePicker
$dpTimeFrom.Location = new-object System.Drawing.Size(120,50)
$dpTimeFrom.Size = new-object System.Drawing.Size(190,20)
$form.Controls.Add($dpTimeFrom)

$dpDatePickerFromlableBox1 = new-object System.Windows.Forms.Label
$dpDatePickerFromlableBox1.Location = new-object System.Drawing.Size(10,70)
$dpDatePickerFromlableBox1.size = new-object System.Drawing.Size(50,20)
$dpDatePickerFromlableBox1.Text = "and"
$form.Controls.Add($dpDatePickerFromlableBox1)

$dpTimeFrom1 = new-object System.Windows.Forms.DateTimePicker
$dpTimeFrom1.Location = new-object System.Drawing.Size(120,70)
$dpTimeFrom1.Size = new-object System.Drawing.Size(190,20)
$form.Controls.Add($dpTimeFrom1)

$dpTimeFrom2 = new-object System.Windows.Forms.DateTimePicker
$dpTimeFrom2.Format = "Time"
$dpTimeFrom2.value = [DateTime]::get_Now().AddHours(-1)
$dpTimeFrom2.ShowUpDown = $True
$dpTimeFrom2.Location = new-object System.Drawing.Size(315,50)
$dpTimeFrom2.Size = new-object System.Drawing.Size(90,20)
$form.Controls.Add($dpTimeFrom2)

$dpTimeFrom3 = new-object System.Windows.Forms.DateTimePicker
$dpTimeFrom3.Format = "Time"
$dpTimeFrom3.ShowUpDown = $True
$dpTimeFrom3.Location = new-object System.Drawing.Size(315,70)
$dpTimeFrom3.Size = new-object System.Drawing.Size(90,20)
$form.Controls.Add($dpTimeFrom3)



# Add DataGrid View

$dgDataGrid = new-object System.windows.forms.DataGridView
$dgDataGrid.Location = new-object System.Drawing.Size(10,100)
$dgDataGrid.size = new-object System.Drawing.Size(1000,600)
$dgDataGrid.AutoSizeColumnsMode = "AllCells"

$form.Controls.Add($dgDataGrid)

#populate DataGrid

$form.topmost = $true
$form.Add_Shown({$form.Activate()})
$form.ShowDialog()


Wednesday, July 18, 2007

Turning on Filter Junk Email in Exchange 2007 via an OWA Script

In the past I’ve posted a few scripts for setting and reading the OWA junk email filter settings here. While content filtering and the IMF have changed in Exchange 2007 there are still no cmdlets that will allow you to flip this option on or off for users so this little script still can come in handy for various situations. Because OWA was rewritten from the ground up in Exchange 2007 the old script method no longer works. However the same methods of reverse engineering the OWA method do work with a few additions.

Using the MSXML2.ServerXMLHTTP.6.0 object this object is included with the Microsoft XML Parser (MSXML) and is a better choice for this script because it firstly supports the ability to ignore any SSL errors that might happen (eg self signed Certs, Alternate names etc) and it also handles dealing with the Forms Based Authentication cookie without the necessity to add additional code. The code still needs to perform the synthetic forms logon this works similar to 2003 with a few URL tweaks.

Dealing with the Language form for users who have never logged on to OWA before. Because this script is simulating a user in OWA if the mailbox your trying to set the junk email settings has never been logged onto before in OWA then the default language form will be presented to the user (or the script in this case) asking the person to choose there timezone and language. What this script does to cater for this is that it looks for this form in the response if it finds the form it then uses 2 regular expressions to parse the default values from the form and then posts these values. One problem this creates is that the user will nolonger be shown this form when they first logon anymore this may or may not be a problem for you. If you need for this form to still appear at first logon there are two options the first is to delete the OWA storage object in the root of the mailbox using WebDAV or Neil Hobson posted another method on the Exchange Blog.

The operation of the script is pretty simple after logging in it tries to post to the following URL QueryString in the Target Mailbox “/ev.owa?oeh=1&ns=JunkEmail&ev=Enable” with a body

"<params><fEnbl>1</fEnbl></params>"

This will enable junk email filtering on a mailbox to disable junk email filtering use

"<params><fEnbl>0</fEnbl></params>"

To use this script you need to hard code the username and password of a user that has been give delegate access to the target mailbox using something like this in the Exchange Command Shell

Add-MailboxPermission –Identity ‘Mailbox’ –User ‘User’ –AccessRights FullAccess

Or has been given Send As and Receive As rights on the target mailbox. Basically the user needs to be able to open the target mailbox as another mailbox in OWA you can test if the account you want to use is going to be work by testing this yourself in OWA. Its also important that the account that you want to use has logged onto OWA once as well this is because the Language form would be presented to this user the first time the user tries to logon to OWA while the script caters for this for the target user it doesn’t do it for the source so this would cause a timeout error in the case the source user has never logged on to OWA. So before using the script you need to configure the following variables

snServername = "ServerName"
mnMailboxname = "mailbox"
domain = "domain"
strpassword = "password"

In the snServername variable make sure you use the servername of your CAS server this may or may not be different from your mailbox server.

The following variable is for the target mailbox you want to set the junkemail setting on this should be the primary SMTP address of the target mailbox

Targetmailbox = "user@domain.com"

The scripts output is pretty verbose you should see the full response headers outputted for each request the script make this helps if you ever need to diagnose why the script isn’t working

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

snServername = "ServerName"
mnMailboxname = "mailbox"
domain = "domain"
strpassword = "password"

strusername = domain & "\" & mnMailboxname
szXml = "destination=https://" & snServername & "/owa/&flags=0&username=" &
strusername
szXml = szXml & "&password=" & strpassword & "&SubmitCreds=Log On&forcedownlevel=0&trusted=0"


set req = createobject("MSXML2.ServerXMLHTTP.6.0")
req.Open "post", "https://" & snServername & "/owa/auth/owaauth.dll", False
req.SetOption 2, 13056
req.send szXml

reqhedrarry = split(req.GetAllResponseHeaders(), vbCrLf,-1,1)
for each ent in reqhedrarry
wscript.echo ent
Next

Call UpdateJunk("user@domain.com")

Sub UpdateJunk(mbMailbox)

xmlstr = "<params><fEnbl>1</fEnbl></params>"

req.Open "POST", "https://" & snServername & "/owa/" & mbMailbox & "/ev.owa?oeh=1&ns=JunkEmail&ev=Enable",
False
req.setRequestHeader "Content-Type", "text/xml; charset=""UTF-8"""
req.setRequestHeader "Content-Length", Len(xmlstr)
req.send xmlstr
wscript.echo req.status
reqhedrarry = split(req.GetAllResponseHeaders(), vbCrLf,-1,1)
for each ent in reqhedrarry
wscript.echo ent
Next
If InStr(req.responsetext,"name=lngFrm") Then
wscript.echo "Mailbox has not been logged onto before via OWA"
'Create a regular expression object
Dim objRegExp
Set objRegExp = New RegExp

'Set our pattern
objRegExp.Pattern = "<option selected value=""(.*?)"">"
objRegExp.IgnoreCase = True
objRegExp.Global = True

Dim objMatches
Set objMatches = objRegExp.Execute(req.responsetext)
If objMatches.count = 2 then
lcidarry = Split(objMatches(0).Value,Chr(34))
wscript.echo lcidarry(1)
tzidarry = Split(objMatches(1).Value,Chr(34))
wscript.echo tzidarry(1)
pstring = "lcid=" & lcidarry(1) & "&tzid=" & tzidarry(1)
req.Open "POST", "https://" & snServername & "/owa/" & mbMailbox & "/lang.owa",
False
req.setRequestHeader "Content-Type", "application/x-www-form-urlencoded"
req.setRequestHeader "Content-Length", Len(pstring)
' req.SetRequestHeader "cookie", reqCadata
req.send pstring
if instr(req.responsetext,"errMsg") then
wscript.echo "Permission Error"
else
wscript.echo req.status
If req.status = 200 and not instr(req.responsetext,"errMsg") Then
Call UpdateJunk(mbMailbox)
Else
wscript.echo "Failed to set Default OWA settings"
End if
end if

Else
wscript.echo "Script failed to retrieve default values"
End if
Else
wscript.echo "Junk Mail Setting Updated"
End if
End sub


Tuesday, July 10, 2007

Setting the Homepage on a Outlook Folder via a script

I’ve had a number of people ask this question in the past so I thought I’d post up a script to help out those they may want to look at doing this.

When you set the Outlook homepage within Outlook it configures the PR_FOLDER_WEBVIEWINFO or http://schemas.microsoft.com/mapi/proptag/0x36DF0102 property. This property is a Binary property who’s format is undocumented but using a Mapi editor like OutlookSpy or MfcMapi you can work out the format that this follows. The basic format is

dwVersion: 0x00000002
dwType: 0x00000001
dwFlags: 0x00000001
dwUnused: 0x0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000, 0x00000000
cbData: 0x188 (000000BC)
bData: http://yoururl.com

If you want to set this property in a script the 3 values you need to worry about are

dwFlags If this is set to 1 then the check box in Outlook for “Show homepage by default for this folder” will be checked.

cbData is the number of bytes (8 bits or 2 hex digits) or the url in Bdata + the spacers

bData is the URL of the webpage you want to point to encoded in Hex.

The following script handles encoding URL’s that are up to 255 characters long if you want to have URL’s that are longer than 255 charterers then you need to change the code for cbData. The rest of the code builds the binary property. The AsciiToHex to function encodes the Ascii string 1 byte for each letter hence the extra padding needed.

The one thing to note is this is a unsupported thing to do so make sure you do plenty of your own testing first.

I’ve created 2 versions of the script one version uses codex and the other cdo1.2 they do basically the same thing. They first check for an instance of a folder in a mailbox (the cdo1.2 version only checks the Root folder). If an instance of that folder is found then its sets the homepage property on the folder else it creates the folder and sets the homepage. In this sample the folder is called webfolder and it sets the homepage of that folder to a search about coffee tasting in Sydney.

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

homepage = "http://yoururl.com"
dwVersion = "02"
dwType = "00000001"
dwFlags = "00000001"
dwUnused = "00000000000000000000000000000000000000000000000000000000"
bData = AsciiToHex(homepage)
cbDataSize = cstr(ubound(bData)+1)
propval = dwVersion & dwType & dwFlags & dwUnused & "000000" & Hex(cbDataSize) & "000000" & Join(bData,"")

set rec = createobject("ADODB.Record")
rec.open "file://./backofficestorage/domain.com/MBX/mailbox/webfolder/", ,3,33562624
rec.fields("http://schemas.microsoft.com/mapi/proptag/0x36DF0102").value = propval
rec.fields.update
rec.close


Function AsciiToHex(sData)
Dim i, aTmp()
ReDim aTmp((Len(sData)*2) + 1)
arnum = 0
For i = 1 To Len(sData)
aTmp(arnum) = Hex(Asc(Mid(sData, i)))
arnum = arnum + 1
aTmp(arnum) = "00"
arnum = arnum + 1
Next
aTmp(arnum) = "00"
arnum = arnum + 1
aTmp(arnum) = "00"
ASCIItoHex = aTmp
End Function

Thursday, July 05, 2007

Synconize items from a public folder to a mailbox folder with WebDAV replication

A while ago I wrote this script to synchronize contacts from a mailbox folder to a central contacts folder using Webdav replication and CDO 1.2 as the copy mechanism. A few people have asked about going the other way eg from a central contacts folder or calendar folder to a local mailbox folder so I've managed to find a bit of time this week to create a port that would do this. The underlying functionality of how this work is written up in the other post so i won't repeat this the main points with the new script are

  • There are four scripts in the download like the previous post there is both FBA and NTLM/Basic version to cater for different authentication. Theres also a separate version for contacts/mail objects and calendar objects.
  • The main differences with the calendar version is that as well as copying the calendar item to the target folder it changes the colour of the appointment to blue and also sets the freebusy status of this appointment to FREE. The following lines are responsible for this
objCopyappt.Fields.Add "0x8214", vbLong, 2, "0220060000000000C000000000000046"
objCopyappt.Fields.Add "0x8205", vbLong, 0, "0220060000000000C000000000000046"

  • WebDAV replication by default only replicates in chunks of 512 items within one request. This script caters for folders where there are more then 512 items by looking at the number of items returned in the request and then making furthers request until all items in the folder are replicated.
Depending on the version your using you will need to configure all the following variable for the script to work correctly

snServername = "servername"
mnMailboxname = "username"
domain = "domain"
strpassword = "password"
strusername = domain & "\" & mnMailboxname
DestinURL = "https://" & snServername & "/exchange/" & mnMailboxname & "/mailboxfolder/"
SourceURL = "https://" & snServername & "/public/foldername/"

I've put a download copy of the code here the code itself looks like

snServername = "servername"
mnMailboxname = "username"
domain = "domain"
strpassword = "password"
strusername = domain & "\" & mnMailboxname
DestinURL = "https://" & snServername & "/exchange/" & mnMailboxname & "/mailboxfolder/"
SourceURL = "https://" & snServername & "/public/foldername/"


szXml = "destination=https://" & snServername & "/exchange/&flags=0&username=" &
strusername
szXml = szXml & "&password=" & strpassword & "&SubmitCreds=Log On&forcedownlevel=0&trusted=0"
set req = createobject("microsoft.xmlhttp")
req.Open "post", "https://" & snServername & "/exchweb/bin/auth/owaauth.dll",
False
req.send szXml
reqhedrarry = split(req.GetAllResponseHeaders(), vbCrLf,-1,1)
for c = lbound(reqhedrarry) to ubound(reqhedrarry)
if instr(lcase(reqhedrarry(c)),"set-cookie: sessionid=") then reqsessionID =
right(reqhedrarry(c),len(reqhedrarry(c))-12)
if instr(lcase(reqhedrarry(c)),"set-cookie: cadata=") then reqcadata=
right(reqhedrarry(c),len(reqhedrarry(c))-12)
Next

set req = createobject("microsoft.xmlhttp")
set objSession = CreateObject("MAPI.Session")
strProfile = snServername & vbLf & mnMailboxname
objSession.Logon "",,, False,, True, strProfile
Set objInfoStore = objSession.GetInfoStore(objSession.Inbox.StoreID)
Set objpubstore = objSession.InfoStores("Public Folders")
dfFolderID = getfid()
wscript.echo dfFolderID
colbblob = Collabblobget()
QueryPF(colbblob)


sub QueryPF(colbblob)

strQuery = "<?xml version=""1.0""?><D:searchrequest xmlns:D = ""DAV:"" xmlns:R=""http://schemas.microsoft.com/repl/""><R:repl><R:collblob>"
& colbblob & "</R:collblob></R:repl>"
strQuery = strQuery & "<D:sql>SELECT ""DAV:href"", ""urn:schemas:httpmail:subject"",
""http://schemas.microsoft.com/mapi/proptag/x0fff0102"",""http://schemas.microsoft.com/repl/repl-uid""
"
strQuery = strQuery & " FROM scope('shallow traversal of """
strQuery = strQuery & SourceURL & """') Where ""DAV:ishidden"" = False AND
""DAV:isfolder"" = False "
strQuery = strQuery & "</D:sql></D:searchrequest>"
req.open "SEARCH", SourceURL, false
req.setrequestheader "Content-Type", "text/xml"
req.SetRequestHeader "cookie", reqsessionID
req.SetRequestHeader "cookie", reqCadata
req.setRequestHeader "Translate","f"
req.send strQuery
If req.status >= 500 Then
wscript.echo "Status: " & req.status
wscript.echo "Status text: An error occurred on the server."
ElseIf req.status = 207 Then
wscript.echo "Status: " & req.status
wscript.echo "Status text: " & req.statustext
set oResponseDoc = req.responseXML
set oNodeList = oResponseDoc.getElementsByTagName("d:collblob")
For i = 0 To (oNodeList.length -1)
set oNode = oNodeList.nextNode
colblob = oNode.Text
Collabblobset(colblob)
Next
set idNodeList = oResponseDoc.getElementsByTagName("f:x0fff0102")
set replidNodeList = oResponseDoc.getElementsByTagName("d:repl-uid")
set replchangeType = oResponseDoc.getElementsByTagName("d:changetype")
for id = 0 To (idNodeList.length -1)
set oNode1 = idNodeList.nextNode
set oNode2 = replidNodeList.nextNode
set oNode3 = replchangeType.nextNode
select case oNode3.text
case "new" call Copyappt(Octenttohex(oNode1.nodeTypedValue),oNode2.text)
case "delete" wscript.echo oNode3.text
wscript.echo oNode2.text
Deleteappt(oNode2.text)
case "change" Wscript.echo "Change"
call Deleteappt(oNode2.text)
call Copyappt(Octenttohex(oNode1.nodeTypedValue),oNode2.text)
end select
next
Else
wscript.echo "Status: " & req.status
wscript.echo "Status text: " & req.statustext
wscript.echo "Response text: " & req.responsetext
End If
wscript.echo idNodeList.length
if idNodeList.length = 512 then QueryPF(colblob)

End Sub

Sub Copyappt(messageEntryID,ReplID)

set objappt = objSession.getmessage(messageEntryID,objpubstore.ID)
set objCopyappt = objappt.copyto(dfFolderID)
objCopyappt.Unread = false
objCopyappt.Fields.Add "0x8542", vbString,
ReplID,"0820060000000000C000000000000046"
objCopyappt.Fields.Add "0x8214", vbLong, 2, "0220060000000000C000000000000046"
objCopyappt.Fields.Add "0x8205", vbLong, 0, "0220060000000000C000000000000046"
objCopyappt.Update
Set objCopyappt = Nothing
wscript.echo objappt.subject

end Sub

Sub Deleteappt(replUID)

strQuery = "<?xml version=""1.0""?><D:searchrequest xmlns:D = ""DAV:"">"
strQuery = strQuery & "<D:sql>SELECT ""DAV:Displayname"""
strQuery = strQuery & " FROM scope('shallow traversal of """
strQuery = strQuery & DestinURL & """') Where
""http://schemas.microsoft.com/mapi/id/{00062008-0000-0000-C000-000000000046}/0x8542""
= '" & replUID & "' AND ""DAV:isfolder"" = False "
strQuery = strQuery & "</D:sql></D:searchrequest>"
req.open "SEARCH", DestinURL, false, "", ""
req.setrequestheader "Content-Type", "text/xml"
req.SetRequestHeader "cookie", reqsessionID
req.SetRequestHeader "cookie", reqCadata
req.setRequestHeader "Translate","f"
req.send strQuery
If req.status >= 500 Then
wscript.echo "Status: " & req.status
wscript.echo "Status text: An error occurred on the server."
ElseIf req.status = 207 Then
wscript.echo "Status: " & req.status
wscript.echo "Status text: " & req.statustext
set oResponseDoc = req.responseXML
set oNodeList = oResponseDoc.getElementsByTagName("a:href")
For i = 0 To (oNodeList.length -1)
set oNode = oNodeList.nextNode
wscript.echo oNode.text
req.open "DELETE", oNode.text, false
req.send
wscript.echo "Status: " & req.status
Next
Else
wscript.echo "Status: " & req.status
wscript.echo "Status text: " & req.statustext
wscript.echo "Response text: " & req.responsetext
End If


end Sub

Sub Collabblobset(colblob)
xmlstr = "<?xml version=""1.0""?>" _
& "<g:propertyupdate " _
& " xmlns:g=""DAV:"" xmlns:e=""http://schemas.microsoft.com/exchange/""" _
& " xmlns:dt=""urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/"" " _
& " xmlns:cp=""" & SourceURL & """ " _
& " xmlns:header=""urn:schemas:mailheader:"" " _
& " xmlns:mail=""urn:schemas:httpmail:""> " _
& " <g:set> " _
& " <g:prop> " _
& " <cp:collblob>" & colblob & "</cp:collblob> " _
& " </g:prop> " _
& " </g:set> " _
& "</g:propertyupdate>"

req.open "PROPPATCH", DestinURL, False
req.setRequestHeader "Content-Type", "text/xml;"
req.SetRequestHeader "cookie", reqsessionID
req.SetRequestHeader "cookie", reqCadata
req.setRequestHeader "Translate", "f"
req.setRequestHeader "Content-Length:", Len(xmlstr)
req.send(xmlstr)
wscript.echo req.responsetext

end sub



function Collabblobget()

xmlreqtxt = "<?xml version='1.0'?><a:propfind xmlns:a='DAV:' xmlns:cp='" &
SourceURL & "'><a:prop><cp:collblob/></a:prop></a:propfind>"
req.open "PROPFIND", DestinURL, false, "", ""
req.setRequestHeader "Content-Type", "text/xml; charset=""UTF-8"""
req.setRequestHeader "Depth", "0"
req.SetRequestHeader "cookie", reqsessionID
req.SetRequestHeader "cookie", reqCadata
req.setRequestHeader "Translate", "f"
req.send xmlreqtxt
set oResponseDoc = req.responseXML
set oCobNode = oResponseDoc.getElementsByTagName("d:collblob")
For i1 = 0 To (oCobNode.length -1)
set oNode = oCobNode.nextNode
Collabblobget = oNode.Text
Next

End function



function getfid()

xmlreqtxt = "<?xml version='1.0'?><a:propfind xmlns:a='DAV:'
xmlns:e='http://schemas.microsoft.com/mapi/proptag/'><a:prop><e:x0FFF0102/></a:prop></a:propfind>"
req.open "PROPFIND", DestinURL, false , "", ""
req.setRequestHeader "Content-Type", "text/xml; charset=""UTF-8"""
req.SetRequestHeader "cookie", reqsessionID
req.SetRequestHeader "cookie", reqCadata
req.setRequestHeader "Depth", "0"
req.setRequestHeader "Translate", "f"
req.send xmlreqtxt
set oResponseDoc = req.responseXML
set oNodeList = oResponseDoc.getElementsByTagName("d:x0FFF0102")
For i = 0 To (oNodeList.length -1)
set oNode = oNodeList.nextNode
getfid = Octenttohex(oNode.nodeTypedValue)
Next

end function

Function Octenttohex(OctenArry)
ReDim aOut(UBound(OctenArry))
For i = 1 to UBound(OctenArry) + 1
if len(hex(ascb(midb(OctenArry,i,1)))) = 1 then
aOut(i-1) = "0" & hex(ascb(midb(OctenArry,i,1)))
else
aOut(i-1) = hex(ascb(midb(OctenArry,i,1)))
end if
Next
Octenttohex = join(aOUt,"")
End Function