Friday, December 18, 2009

Using ADSI to find your CAS or Mailbox Role servers in VBS or PowerShell

While the Exchange Management Shell is a thing of wonder its not always available when your writing a script or piece of real code and you need to do something like finding your Exchange 2007/2010 CAS or Mailbox role servers. The good news is like most of the Exchange configuration information this is stored in Active directory and can be relatively easily queried using LDAP and ADSI.

The AD property that holds this information about what particular roles are installed on a Exchange server is the msExchCurrentServerRoles property. This property contain a number of bitwise flags that indicate which roles are installed as per http://technet.microsoft.com/en-us/library/bb123496(EXCHG.80).aspx .

Server role Role value

Mailbox role 2
Client Access role (CAS) 4
Unified Messaging role 16
Hub Transport role 32
Edge Transport role 64

So to query these in ADSI we need to use a Bitwise filter as per http://support.microsoft.com/kb/269181

So the LDAP filter to return all the server with the mailbox role would be

(msExchCurrentServerRoles:1.2.840.113556.1.4.803:=2)

for CAS Servers you would use

msExchCurrentServerRoles:1.2.840.113556.1.4.803:=4)

To put this into a larger script in VBS

Set Conn = CreateObject("ADODB.Connection")
Set com = CreateObject("ADODB.Command")
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strNameingContext = iAdRootDSE.Get("configurationNamingContext")
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
svcQuery = "<LDAP://CN=Microsoft Exchange,CN=Services," & strNameingContext & ">;(&(&(objectCategory=msExchExchangeServer)" _
& "(msExchCurrentServerRoles:1.2.840.113556.1.4.803:=4)));cn,name,serialNumber,distinguishedName,legacyExchangeDN;subtree"
com.ActiveConnection = Conn
com.CommandText = svcQuery
Set rs = com.Execute
While Not rs.EOF
wscript.echo rs.Fields("cn")
rs.MoveNext
Wend


In powershell something like this should work

$root = [ADSI]'LDAP://RootDSE'
$cfConfigRootpath = "LDAP://" + $root.ConfigurationNamingContext.tostring()
$configRoot = [ADSI]$cfConfigRootpath
$searcher = new-object System.DirectoryServices.DirectorySearcher($configRoot)
$searcher.Filter = '(&(&(objectCategory=msExchExchangeServer)(msExchCurrentServerRoles:1.2.840.113556.1.4.803:=4)))'
[VOID]$searcher.PropertiesToLoad.Add("cn")
$searchres = $searcher.FindAll()
foreach ($res in $searchres){
$srvOjb = $res.Properties
$srvOjb.cn
}

3 comments:

Anonymous said...

Hi Glen,

Love your work! I am wondering if you can assist I am looking for a powershell script to count how many folders are in a mailbox, I have attempted this myself with no joy not sure if WMI is the way to go??

Glen said...

Have a look at something like http://gsexdev.blogspot.com/2007/12/mailbox-folder-size-comparison.html

Cheers
Glen

Anonymous said...

Is their a wayout to identify differnt version of CAs servers also...like POP/IMAP, OWA, OAB..etc