Friday, March 23, 2007

Finding Stale Address and Telephone information in the GAL with a script

I came across this while actually looking for something else but it does go some way to answering another question that gets asked occasionally. If you want to use the information in the GAL (eg Active Directory) for phone numbers and address’s ect how up to date is this information eg can I find out the last time it was updated. While maybe not 100% accurate one method that you maybe able to use is to use the Metadata from Active Directory which stores information about when the last time each property was updated and replicated in Active directory.

To access the metadata from a script you need to use the iadstools.dll which comes as part of the Windows 2000/3 Support Tools package which can be found on the server CD in Support\Tools folder. Robbie Allen has put together a number of samples on using the objects in this DLL in his Active Directory cookbook which is worth checking out here. For this script I’ve expanded greatly on one of his samples by including a query of ever mailbox in the GAL and then feeding in the DN of each user to grab the metadata about each property and then using a few case statements to filter that data a little further to just the telephone numbers and a few address property such as Street Address and Office. I then feed the data into a CSV file so you can then open this up in Excel and do extra filtering etc.

This is really just scratching the surface of what you can do with this library is terms of diagnosing replication problems etc.

To run the script you need to have the Windows 2000/3 Support Tools installed so you will have the iadstools.dll registered. The script takes one commandline parameter which is the name of the Domain Controller you want to run it against. Eg

Cscript adrlastupdated.vbs domaincontrollernetbiosName

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

dcDomainController = wscript.arguments(0)
set objIadsTools = CreateObject("IADsTools.DCFunctions")
set conn = createobject("ADODB.Connection")
set com = createobject("ADODB.Command")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
Set fso = CreateObject("Scripting.FileSystemObject")
set wfile = fso.opentextfile("c:\temp\AdrinfoLastupdated.csv",2,true)
strNameingContext = iAdRootDSE.Get("defaultNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
Query = "<LDAP://" & strNameingContext &amp; ">;(&(&(& (mailnickname=*)(mailnickname=*)(!msExchHideFromAddressLists=TRUE)(|
(&(objectCategory=person)(objectClass=user)(|(homeMDB=*)(msExchHomeServerName=*)))
))));distinguishedName,displayname;subtree"
Com.ActiveConnection = Conn
Com.CommandText = Query
Com.Properties("Page Size") = 1000
Set Rs = Com.Execute
wfile.writeline("Mailbox,TelephoneNumber,Mobile Number,Home Phone,Street
Address,Office")
While Not Rs.EOF
wfile.writeline(rs.fields("displayname").value & "," &
getUserData(dcDomainController,rs.fields("distinguishedName")))
rs.movenext
Wend
wfile.close
set wfile = nothing
set fso = Nothing



function getUserData(dcDomainController,dnUserDN)
dlDataline = ""
tnTelephoneNumber = "Not Set"
mnMobileNumber = "Not Set"
hnHomePhone = "Not Set"
saStreetAddress = "Not Set"
ofOffice = "Not Set"

intRes = objIadsTools.GetMetaData(Cstr(dcDomainController),Cstr(dnUserDN),0)

if intRes = -1 then
Wscript.Echo objIadsTools.LastErrorText
WScript.Quit
end if
wscript.echo "User" & dnUserDN
for count = 1 to intRes
select case objIadsTools.MetaDataName(count)
case "telephoneNumber" wscript.echo "Telephone Number last write: " &
objIadsTools.MetaDataLastWriteTime(count)
tnTelephoneNumber = objIadsTools.MetaDataLastWriteTime(count)
case "mobile" wscript.echo "Mobile Number last write: " &
objIadsTools.MetaDataLastWriteTime(count)
mnMobileNumber = objIadsTools.MetaDataLastWriteTime(count)
case "homePhone" wscript.echo "Home Phone Number last write: " &
objIadsTools.MetaDataLastWriteTime(count)
hnHomePhone = objIadsTools.MetaDataLastWriteTime(count)
case "streetAddress" wscript.echo "Street Address last write: " &
objIadsTools.MetaDataLastWriteTime(count)
saStreetAddress = objIadsTools.MetaDataLastWriteTime(count)
case "physicalDeliveryOfficeName" wscript.echo "Office last write: " &
objIadsTools.MetaDataLastWriteTime(count)
ofOffice = objIadsTools.MetaDataLastWriteTime(count)
end select
next
wscript.echo
dlDataline = tnTelephoneNumber &amp; "," & mnMobileNumber & "," & hnHomePhone & ","
& saStreetAddress &amp; "," & ofOffice
getUserData = dlDataline
end function


Thursday, March 01, 2007

Powershell form for Reporting on all Appointments in all mailboxes on a Server using WebDAV

This is another script that's similar to the last few that I've posted in that its designed to query all the mailboxes on a given server and then report the information it finds. The way this script differs is that firstly its a powershell script and secondly it creates a little Winform gui to allow you to interact with the results of the query so its no longer just a static report. The layout it reports back in is two Listviews the first list view shows a summary of the number of appointments the WebDAV query finds for each mailbox and the second is activated when you click a row in the first list view which then shows a list of the appointments in the calendar of the mailbox selected. To make this a little more useful I've added a bunch of filtering options across the top so you can take the original data captured in the appointment query and filter it in a few different ways. Eg you can filter it by the last modified date so you could answer a question such as

Show me all the appointments that where modified after a certain date Or
Show me all the appointments that where modified before a certain date

The two other filtering options are for Free/Busy so you can show all the appointments that are set to free in the time period or all the appointments that aren't set to free. the last filter option is for the Time Zone Mapi property that Matt Stehle blogged about the other day this should show you all the appointments that the rebasing tool has been run on and any that it hasn't. You can combine multiple filters so you could show the number of appointments that where modified after a certain date by the rebasing tool etc.

The Script uses WebDAV via the Admin virtual root directory to access the user calendars this gets around the need for the user running the script to have rights in the users mailbox and should be able to be run successfully using just delegated Exchange Admin rights. To work out the correct path to use for the Admin virtual root the script includes a LDAP query that gets the default SMTP FQDN from the default recipient policy.
By default the script isn’t using SSL which may mean you need to adjust the following line if you are using SSL on the ExAdmin Directory
Eg change line 162
$arMbRoot = "http://" + $snServerNameDrop.SelectedItem.ToString() + "/exadmin/admin/" + $dfAddress + "/mbx/"

to

$arMbRoot = "https://" + $snServerNameDrop.SelectedItem.ToString() + "/exadmin/admin/" + $dfAddress + "/mbx/"

The script works by querying appointments and then filling a datatable the filtering options work by filtering the data in the datatable using Table selects built by examining the state of different controls and repopulating that data in the listviews I've taken the complete automation approach with this script so there are no command line parameters or servername variables to fill out. When the script runs it will populate the servername list box with the name of all the Exchange servers it finds by querying the configuration partition of the domain its being run in. When you use the script itself you only need to hit the get-appointment button once. After you hit the button in the background the script will attempt to get the appointments for the server you select this can be a lengthy operation to give some progress the script writes back to the console windows as it processes each mailbox. So you may want to push the form to one side and what the status of the powershell console window as it processes each mailbox. When you want to re-filter the data using the filtering options make sure you hit the filter button to filter the data and not the get-appointment buttons. The filter button will re-filter the data in a matter of seconds while the get-appointments but will re-query all the appointments which will take a considerable amount of time. If you want to query other times outside of the DST affected ones you can with this script using the datetime pickers for start and end time..
I've put a downloadable copy of the script here the script itself blew out to over 500 lines so its a little two large to post.

Combined Summary and Audit VBS Script for all appointments in all calendars on a Server via WebDAV

This is a combination of two of my posts from last week the first was Euricelia's "Creating a Report of Meeting Organizers for all appointments in all calendars on a Server via WebDAV" script and then my "Creating a Summary Email of all appointments within a Users Calendar for given period" . This script goes through every mailbox on the server using WebDAV via the Exchange Virtual directory and produces a HTML report of all the meeting of all users on the server during the configured time period with Outlook hyperlinks to all the appointments. I've added two extra columns to this report the first is the free/busy status of the appointment (useful if you have change the free busy status of appointment in resource mailboxes) and also the new Time Zone Mapi property that Matt Stehle blogged about the other day. (This is displayed in the report as NewClients) which should show whether the rebasing tool has modified the appointment (whether its now set to the correct time is another matter completely unless the Server develops ESP you can never be 100% sure)

To run this script you need to set the the following commandline variables

servername = "SERVERNAME"
username = "USERNAME"
password = "PASSWORD"

If you using NTLM authentication in OWA then you can leave the Username and Password blank (make sure you set them to null though). This script wont really work if you using FBA for this you should look at the virtual admin root or see the powershell sample in my next post.

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

on error resume next
servername = "SERVERNAME"
public username
public password
username = "USERNAME"
password = "PASSWORD"
public datefrom
public dateto
datefrom = "2007-03-11T00:00:00Z"
dateto = "2007-04-01T00:00:00Z"
trReportBody = ""

set shell = createobject("wscript.shell")
set conn1 = createobject("ADODB.Connection")


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 &amp;amp;amp;amp; ">;(&(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") &amp;amp;amp;amp; ")) )))))"
strQuery = "<LDAP://" & strDefaultNamingContext &amp;amp;amp;amp; ">;" & GALQueryFilter &
";distinguishedName,mail,displayname,mailnickname;subtree"
com.Properties("Page Size") = 100
Com.CommandText = strQuery
Set Rs1 = Com.Execute
while not Rs1.eof
wscript.echo "User: " & rs1.fields("displayname")
user = rs1.fields("mail")
call QueryAttendees(servername,user)
rs1.movenext
wend
rs.movenext
wend
rs.close
set conn = nothing
set com = Nothing
rpReport = rpReport &amp;amp;amp;amp; "<table border=""1"" width=""100%"">" & vbcrlf
rpReport = rpReport & " <tr>" & vbcrlf
rpReport = rpReport & "<td align=""center"" bgcolor=""#000080""
width=""15%""><b><font color=""#FFFFFF"">Start Time</font></b></td>" & vbcrlf
rpReport = rpReport & "<td align=""center"" bgcolor=""#000080""
width=""15%""><b><font color=""#FFFFFF"">End time</font></b></td>" & vbcrlf
rpReport = rpReport & "<td align=""center"" bgcolor=""#000080""
width=""30%""><b><font color=""#FFFFFF"">Subject</font></b></td>" & vbcrlf
rpReport = rpReport & "<td align=""center"" bgcolor=""#000080""
width=""10%""><b><font color=""#FFFFFF"">Location</font></b></td>" & vbcrlf
rpReport = rpReport & "<td align=""center"" bgcolor=""#000080""
width=""10%""><b><font color=""#FFFFFF"">Organizer</font></b></td>" & vbcrlf
rpReport = rpReport & "<td align=""center"" bgcolor=""#000080""
width=""10%""><b><font color=""#FFFFFF"">Free/Busy</font></b></td>" & vbcrlf
rpReport = rpReport & "<td align=""center"" bgcolor=""#000080""
width=""10%""><b><font color=""#FFFFFF"">New Clients</font></b></td>" & vbcrlf
rpReport = rpReport & "</tr>" & vbcrlf
rpReport = rpReport & trReportBody
rpReport = rpReport & "</table>" & vbcrlf
Set fso = CreateObject("Scripting.FileSystemObject")

set wfile = fso.opentextfile("c:\temp\" & servername & ".htm",2,true)
wfile.write rpReport
wfile.close
set wfile = nothing
set fso = Nothing
wscript.echo "Done"


Public Sub QueryAttendees(server,mailbox)

On Error Resume Next

strURL = "http://" & server &amp; "/exchange/" & mailbox & "/calendar/"
strQuery = "<?xml version=""1.0""?><D:searchrequest xmlns:D = ""DAV:""
xmlns:b=""urn:uuid:c2f41010-65b3-11d1-a29f-00aa00c14882/"">"
strQuery = strQuery & "<D:sql>SELECT ""DAV:displayname"",
""urn:schemas:httpmail:subject"", "
strQuery = strQuery & """DAV:creationdate"", "
strQuery = strQuery & """http://schemas.microsoft.com/mapi/proptag/0x0FFF0102""
As EntryID, "
strQuery = strQuery & """urn:schemas:httpmail:fromname"",
""urn:schemas:calendar:dtstart"", ""urn:schemas:calendar:dtend"", "
strQuery = strQuery &
"""http://schemas.microsoft.com/mapi/id/{00062002-0000-0000-C000-000000000046}/0x8205""
As BusyStatus,"
strQuery = strQuery &
"""http://schemas.microsoft.com/mapi/id/{00062002-0000-0000-C000-000000000046}/0x825E""
As NewClients,"
strQuery = strQuery & " ""urn:schemas:calendar:location"",
""http://schemas.microsoft.com/mapi/apptstateflags"" FROM scope('shallow
traversal of """
strQuery = strQuery & strURL &amp;amp;amp;amp; """') Where ""DAV:ishidden"" = False AND
""DAV:contentclass"" = 'urn:content-classes:appointment' AND "
strQuery = strQuery & " NOT ""urn:schemas:calendar:instancetype"" = 1 AND "
strQuery = strQuery & """urn:schemas:calendar:dtstart"" &lt;= CAST(""" & dateto
& """ as 'dateTime') AND "
strQuery = strQuery &amp; """urn:schemas:calendar:dtend"" &gt;= CAST(""" & datefrom
& """ as 'dateTime')</D:sql></D:searchrequest>"


wscript.echo strQuery
set req = createobject("microsoft.xmlhttp")
req.open "SEARCH", strURL, false, username, password

If Err.Number <> 0 Then
WScript.Echo "Error Opening Search"
WScript.Echo Err.Number & ": " & Err.Description
End If

req.setrequestheader "Content-Type", "text/xml"
req.setRequestHeader "Translate","f"
req.setRequestHeader "Depth", "1,noroot"
req.send strQuery

If Err.Number <> 0 Then
WScript.Echo "Error Sending Query"
WScript.Echo Err.Number & ": " & Err.Description
End If

wscript.echo req.status
wscript.echo "response" & req.responseXML

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
set oResponseDoc = req.responseXML
set oDisplayNameNodes = oResponseDoc.getElementsByTagName("a:displayname")
set oHrefNodes = oResponseDoc.getElementsByTagName("a:href")
set oSubject = oResponseDoc.getElementsByTagName("d:subject")
set oEndTime = oResponseDoc.getElementsByTagName("e:dtend")
Set oStartTime = oResponseDoc.getElementsByTagName("e:dtstart")
Set oLocation = oResponseDoc.getElementsByTagName("e:location")
Set oAppstate = oResponseDoc.getElementsByTagName("f:apptstateflags")
Set oFromname = oResponseDoc.getElementsByTagName("d:fromname")
Set oEntryID = oResponseDoc.getElementsByTagName("EntryID")
Set oBusyStatus = oResponseDoc.getElementsByTagName("BusyStatus")
Set oNewClients = oResponseDoc.getElementsByTagName("NewClients")
For i = 0 To (oDisplayNameNodes.length -1)
set oNode = oDisplayNameNodes.nextNode
set oNode1 = oHrefNodes.nextNode
set oNode2 = oSubject.nextNode
set oNode3 = oEndTime.nextNode
Set oNode4 = oStarttime.nextNode
Set oNode5 = oLocation.nextNode
Set oNode6 = oAppstate.nextNode
Set oNode7 = oFromname.nextNode
Set oNode8 = oEntryID.nextNode
Set oNode9 = oBusyStatus.nextNode
Set oNode10 = oNewClients.nextNode
if oNode10.text = "" then
ncNewclients = "False"
else
ncNewclients = "True"
end if
wscript.echo Octenttohex(oNode8.nodeTypedValue)
soOrgnizer = ""
soOrgnizer = oNode7.text
sdStartDate =
dateadd("h",toffset,DateSerial(Mid(oNode4.text,1,4),Mid(oNode4.text,6,2),Mid(oNode4.text,9,2))
&amp;amp;amp;amp; " " & Mid(oNode4.text,12,8))
edEndDate =
dateadd("h",toffset,DateSerial(Mid(oNode3.text,1,4),Mid(oNode3.text,6,2),Mid(oNode3.text,9,2))
&amp;amp;amp;amp; " " & Mid(oNode3.text,12,8))
wscript.echo soOrgnizer
wscript.echo
trReportBody = trReportBody &amp;amp;amp;amp; "<tr>" & vbcrlf
trReportBody = trReportBody & "<td align=""center"" width=""15%"">" &
sdStartDate &amp;amp;amp;amp; " </td>" & vbcrlf
trReportBody = trReportBody & "<td align=""center"" width=""15%"">" & edEndDate
& "&nbsp;</td>" & vbcrlf
trReportBody = trReportBody & "<td align=""center"" width=""30%""><a
href=""outlook:" & Octenttohex(oNode8.nodeTypedValue) & """>" & oNode2.text &
"</a> </td>" & vbcrlf
trReportBody = trReportBody & "<td align=""center"" width=""10%"">" &
oNode5.text & "&nbsp;</td>" & vbcrlf
trReportBody = trReportBody & "<td align=""center"" width=""10%"">" & soOrgnizer
&amp;amp;amp;amp; " </td>" & vbcrlf
trReportBody = trReportBody & "<td align=""center"" width=""10%"">" &
GetBusyStatusText(oNode9.text) &amp;amp;amp;amp; " </td>" & vbcrlf
trReportBody = trReportBody & "<td align=""center"" width=""10%"">" &
ncNewclients &amp;amp;amp;amp; " </td>" & vbcrlf
trReportBody = trReportBody & "</tr>" & vbcrlf

Next
Else
wscript.echo "Status: " & req.status
wscript.echo "Status text: " & req.statustext
wscript.echo "Response text: " & req.responsetext
End If

End Sub

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

Function GetBusyStatusText(bsBusyStatusProp)

select case bsBusyStatusProp
case 0 GetBusyStatusText = "Free"
case 1 GetBusyStatusText = "Tentative"
case 2 GetBusyStatusText = "Busy"
case 3 GetBusyStatusText = "Out of Office"
Case Else GetBusyStatusText = "Unknown"
end Select

End Function