Friday, March 18, 2005

C# WMI Exchange samples

Somebody asked this morning about using WMI and Exchange in c#. There's a lot of good information on the Web about using the System.Management namespace to access WMI but not many Exchange specific C# samples at the moment. I decided to convert a few of the examples I've used in the scripts in my blog.

The first is a simple mailbox size example

System.Management.ConnectionOptions objconn = new System.Management.ConnectionOptions();
objconn.Impersonation = System.Management.ImpersonationLevel.Impersonate;
objconn.EnablePrivileges = true;
string cServername = "servername";
System.Management.ManagementScope exmangescope = new System.Management.ManagementScope(@"\\" + cServername + @"\root\MicrosoftExchangeV2",objconn);
System.Management.ObjectQuery objquery = new System.Management.ObjectQuery("SELECT * FROM Exchange_Mailbox");
System.Management.ManagementObjectSearcher objsearch = new System.Management.ManagementObjectSearcher(exmangescope,objquery);
System.Management.ManagementObjectCollection queryCollection1 = objsearch.Get();
string strDisplay;
foreach( System.Management.ManagementObject instmailbox in queryCollection1 )
{
strDisplay = instmailbox["MailboxDisplayName"].ToString() + " " + instmailbox["size"].ToString();
System.Console.WriteLine(strDisplay);
}

The second is the Mail-Enabling a Public Folder via WMI (Exchange 2003) from this post

System.Management.ConnectionOptions objconn = new System.Management.ConnectionOptions();
objconn.Impersonation = System.Management.ImpersonationLevel.Impersonate;
objconn.EnablePrivileges = true;
string cServername = "servername";
string cPublicFolderPath = "/foldertoenable/";
System.Management.ManagementScope exmangescope = new System.Management.ManagementScope(@"\\" + cServername + @"\root\MicrosoftExchangeV2",objconn);
System.Management.ObjectQuery objquery = new System.Management.ObjectQuery("Select * From Exchange_PublicFolder Where Path='" + cPublicFolderPath + "'");
System.Management.ManagementObjectSearcher objsearch = new System.Management.ManagementObjectSearcher(exmangescope,objquery);
System.Management.ManagementObjectCollection queryCollection1 = objsearch.Get();
foreach( System.Management.ManagementObject instmailbox in queryCollection1 )
{
System.Console.WriteLine(instmailbox["path"].ToString());
System.Console.WriteLine(instmailbox["IsMailEnabled"].ToString());
instmailbox["IsMailEnabled"] = true;
instmailbox.Put();
}


I've posted a txt file version of this up here

Tuesday, March 15, 2005

Data shaping ADSI and Exchange WMI information

I blogged last week about relating mailbox size data with mailbox quota data here. The main problem I had with the approach that I was using here is although it worked fine for 1 user when you wanted to relate a lot of data say the size of everybody’s mailbox on one particular server to the possible size of the mailbox quotas from either their account or mailbox store it gets a little slow.

Data shaping is an ADO thing that allows you to build hierarchical relationships between two or more logical entities in a query. What this means is that I can take two or more separate data sources (via a disconnected recordset) and bung them together in a hierarchical tree (as long as you have a field that relates between the two sources).

The guys over at Rolla do a lot better job of explaining it them me have a look at http://www.4guysfromrolla.com/webtech/060301-1.shtml and
http://www.4guysfromrolla.com/webtech/100699-2.shtml

In my particular scenario I want to shape data from 3 different data sources
1. All the mail store objects for a particular server from the Configuration partition in AD – via ADSI
2. All the visible mailboxes (AD- User object) on a server – Via ADIS
3. All the mailbox sizes – Via Exchange_Mailbox WMI on Exchange 2003

Essentially the hierarchy I wanted to create would look like this

Mail Store Quotas -+
------------------------+---User Account Quotas -+
---------------------------------------------------------+--- Mailbox Size

Because the providers I’m using aren’t going to support the Shape command directly using offline recordsets provides the best method of putting the data into a format that can be shaped.

So what the script does is takes the server-name as a command line parameter and first does a query of Active Directory to get the full distinguished Name of the server. This is then used to find all the mail-stores that belong to this particular server. The information about the mail-store quotas of each of the mail-stores on this server becomes the parent record-set. The next ADSI query that is run is a query of the visible mailboxes in the GAL that are on this server. This information then becomes the child record-set and relates to the parent record-set based on the HomeMDB property of the user object and the DN or the mailstore. The last query to be performed is a grab of all the mailbox sizes on the server from the Exchange_Mailbox WMI class. This information becomes the grandchild record-set and relates to the child recod-set though the legancyDN property of the WMI instance and the AD legacyExchangeDN property of the user object.

The output of the code is all piped to a csv file that by default will be saved to the root of the c:\ drive. Some quick math is done of the mailbox size and quotas size to work out the percentage of the quota that is being used.

In its script form I’m not sure how useful this code is, I hope to turn it into a little Asp.net app that a helpdesk person could use to manage the quota’s for all user's on a server. The other approach maybe to filter the records that are returned further so say you only look at people who are currently at 90 % of there quota and then send a mail to your helpdesk operators to chase up etc.

I’ve posted a download copy of the code here

The script looks like

servername = wscript.arguments(0)
set conn = createobject("ADODB.Connection")
set com = createobject("ADODB.Command")
set conn1 = createobject("ADODB.Connection")
strConnString = "Data Provider=NONE; Provider=MSDataShape"
conn1.Open strConnString
Set iAdRootDSE = GetObject("LDAP://RootDSE")
strNameingContext = iAdRootDSE.Get("configurationNamingContext")
strDefaultNamingContext = iAdRootDSE.Get("defaultNamingContext")
Set fso = CreateObject("Scripting.FileSystemObject")
set wfile = fso.opentextfile("c:\exportquotas.csv",2,true)
wfile.writeline("Username,StorageQuoata(MB),OverLimitQuota(MB),HardLimitQuota(MB),Mailbox
Size(MB),Percent Used")
set objParentRS = createobject("adodb.recordset")
set objChildRS = createobject("adodb.recordset")
strSQL = "SHAPE APPEND" & _
" NEW adVarChar(255) AS SOADDisplayName, " & _
" NEW adVarChar(255) AS SOADDistName, " & _
" NEW adVarChar(255) AS SOmDBStorageQuota, " & _
" NEW adVarChar(255) AS SOmDBOverQuotaLimit, " & _
" NEW adVarChar(255) AS SOmDBOverHardQuotaLimit, " & _
" ((SHAPE APPEND " & _
" NEW adVarChar(255) AS MOADDisplayName, " & _
" NEW adVarChar(255) AS MOADLegacyDN, " & _
" NEW adVarChar(255) AS MOADHomeMDB, " & _
" NEW adBoolean AS MOmDBUseDefaults, " & _
" NEW adVarChar(255) AS MOmDBStorageQuota, " & _
" NEW adVarChar(255) AS MOmDBOverQuotaLimit, " & _
" NEW adVarChar(255) AS MOmDBOverHardQuotaLimit, " & _
" ((SHAPE APPEND " & _
" NEW adVarChar(255) AS WMILegacyDN, " & _
" NEW adVarChar(255) AS WMISize, " & _
" NEW adVarChar(255) AS WMIStorename) " & _
" RELATE MOADLegacyDN TO WMILegacyDN) AS MOWMI" & _
")" & _
" RELATE SOADDistName TO MOADHomeMDB) AS rsSOMO "
objParentRS.LockType = 3
objParentRS.Open strSQL, conn1
Conn.Provider = "ADsDSOObject"
Conn.Open "ADs Provider"
svcQuery = "<LDAP://" & strNameingContext & ">;(&(objectCategory=msExchExchangeServer)(cn="
& Servername & "));cn,name,distinguishedName,legacyExchangeDN;subtree"
Com.ActiveConnection = Conn
Com.CommandText = svcQuery
Set Rs = Com.Execute
while not rs.eof
sgQuery = "<LDAP://" & strNameingContext & ">;(&(objectCategory=msExchPrivateMDB)(msExchOwningServer="
& rs.fields("distinguishedName") & "));cn,name,displayname,distinguishedName,
mDBStorageQuota,mDBOverQuotaLimit,mDBOverHardQuotaLimit,
legacyExchangeDN;subtree"
Com.CommandText = sgQuery
Set Rs1 = Com.Execute
while not rs1.eof
objParentRS.addnew
objParentRS("SOADDisplayName") = rs1.fields("displayname")
objParentRS("SOADDistName") = left(rs1.fields("distinguishedName"),255)
objParentRS("SOmDBStorageQuota") = rs1.fields("mDBStorageQuota")
objParentRS("SOmDBOverQuotaLimit") = rs1.fields("mDBOverQuotaLimit")
objParentRS("SOmDBOverHardQuotaLimit") = rs1.fields("mDBOverHardQuotaLimit")
objParentRS.update
rs1.movenext
wend
wscript.echo "finished 1st AD query storage groups"
GALQueryFilter = "(&(&(&(& (mailnickname=*)(!msExchHideFromAddressLists=TRUE)(|
(&(objectCategory=person)(objectClass=user)(msExchHomeServerName=" &
rs.fields("legacyExchangeDN") & ")) )))))"
strQuery = "<LDAP://" & strDefaultNamingContext & ">;" & GALQueryFilter & ";distinguishedName,msExchMailboxGuid,displayname,
mDBStorageQuota,mDBOverQuotaLimit,mDBOverHardQuotaLimit
,mDBUseDefaults,msExchHomeServerName,legacyExchangeDN,homemdb;subtree"
com.Properties("Page Size") = 100
Com.CommandText = strQuery
Set Rs2 = Com.Execute
objChildRS.LockType = 3
Set objChildRS = objParentRS("rsSOMO").Value
while not rs2.eof
objChildRS.addnew
objChildRS("MOADDisplayName") = rs2.fields("displayname")
objChildRS("MOADLegacyDN") = rs2.fields("legacyExchangeDN")
objChildRS("MOADHomeMDB") = left(rs2.fields("homemdb"),255)
objChildRS("MOmDBUseDefaults") = rs2.fields("mDBUseDefaults")
objChildRS("MOmDBStorageQuota") = rs2.fields("mDBStorageQuota")
objChildRS("MOmDBOverQuotaLimit") = rs2.fields("mDBOverQuotaLimit")
objChildRS("MOmDBOverHardQuotaLimit") = rs2.fields("mDBOverHardQuotaLimit")
objChildRS.update
rs2.movenext
wend
wscript.echo "finished 2nd AD query mailbox"
rs.movenext
wend
Set objgrandchild = objChildRS("MOWMI").Value
strWinMgmts ="winmgmts:{impersonationLevel=impersonate}!//"& servername
&"/root/MicrosoftExchangeV2"
Set objWMIExchange = GetObject(strWinMgmts)
Set listExchange_MailboxSizes = objWMIExchange.ExecQuery("Select * FROM
Exchange_Mailbox",,48)
For each objExchange_MailboxSize in listExchange_MailboxSizes
objgrandchild.addnew
objgrandchild("WMILegacyDN") = objExchange_MailboxSize.LegacyDN
objgrandchild("WMISize") = objExchange_MailboxSize.size
objgrandchild("WMIStorename") = objExchange_MailboxSize.storename
objgrandchild.update
Next
wscript.echo "finished 3nd Exchange WMI query"
objParentRS.MoveFirst
Do While Not objParentRS.EOF
Set objChildRS = objParentRS("rsSOMO").Value
strQuota = objParentRS("SOmDBStorageQuota")
if isnull(objParentRS("SOmDBStorageQuota")) then strQuota = 0
strQuotaLimit = objParentRS("SOmDBOverQuotaLimit")
if isnull(objParentRS("SOmDBOverQuotaLimit")) then strQuotaLimit = 0
strHardQuotaLimit = objParentRS("SOmDBOverHardQuotaLimit")
if isnull(objParentRS("SOmDBOverHardQuotaLimit")) then strHardQuotaLimit = 0
Do While Not objChildRS.EOF
strUsername = replace(objChildRS("MOADDisplayName"),",","")
strUsedefaults = objChildRS("MOmDBUseDefaults")
strusrQuota = objChildRS("MOmDBStorageQuota")
if isnull(objChildRS("MOmDBStorageQuota")) then strusrQuota = 0
strusrQuotaLimit = objChildRS("MOmDBOverQuotaLimit")
if isnull(objChildRS("MOmDBOverQuotaLimit")) then strusrQuotaLimit = 0
strusrHardQuotaLimit = objChildRS("MOmDBOverHardQuotaLimit")
if isnull(objChildRS("MOmDBOverHardQuotaLimit")) then strusrHardQuotaLimit = 0
Set objgrandchild = objChildRS("MOWMI").Value
Do While Not objgrandchild.EOF
mbsize = objgrandchild("WMISize")
if strUsedefaults = false then
if strusrQuota <> 0 then
wfile.writeline strUsername & "," &
replace(formatnumber(strusrQuota/1024,2),",","") & "," &
replace(formatnumber(strusrQuotaLimit/1024,2),",","") & "," &
replace(formatnumber(strusrHardQuotaLimit/1024,2),",","") & "," &
replace(formatnumber(mbsize/1024,2),",","") & "," &
formatnumber((mbsize/strusrQuota)*100,2) & "%"
else
wfile.writeline strUsername & "," &
replace(formatnumber(strusrQuota/1024,2),",","") & "," &
replace(formatnumber(strusrQuotaLimit/1024,2),",","") & "," &
replace(formatnumber(strusrHardQuotaLimit/1024,2),",","") & "," &
replace(formatnumber(mbsize/1024,2),",","") & "," & 0 & "%"
end if
else
if strQuota <> 0 then
wfile.writeline strUsername & "," &
replace(formatnumber(strQuota/1024,2),",","") & "," &
replace(formatnumber(strQuotaLimit/1024,2),",","") & "," &
replace(formatnumber(strHardQuotaLimit/1024,2),",","") & "," &
replace(formatnumber(mbsize/1024,2),",","") & "," &
formatnumber((mbsize/strQuota)*100,2) & "%"
else
wfile.writeline strUsername & "," &
replace(formatnumber(strQuota/1024,2),",","") & "," &
replace(formatnumber(strQuotaLimit/1024,2),",","") & "," &
replace(formatnumber(strHardQuotaLimit/1024,2),",","") & "," &
replace(formatnumber(mbsize/1024,2),",","") & "," & 0 & "%"
end if
end if
objgrandchild.MoveNext
Loop
objChildRS.MoveNext
Loop
objParentRS.MoveNext
Loop
wfile.close
Wscript.echo "CSV file created"

Friday, March 11, 2005

Looking for good Exchange scripts

Paul, Missy and Devin have started posting up some of the scripts from their forthcoming book on the Exchange Cookbook Blog. This should make good reading over the next few weeks. If you haven’t already check out their blog here

Relating Mailbox sizes to Mailbox quotas

Somebody asked last week about how to query mailbox sizes and mailbox quota information for a user. This is a interesting question there’s are a lot of different methods for querying mailboxes sizes most of these are listed in this KB . With Exchange 2003 you can use WMI to pull the mailbox size from the Exchange_mailbox class there’s a sample in the Exchange SDK here. With mailbox quotas what quota information will apply to your mailbox will differ depending on how quotas have been applied to the mailbox. Quotas can come from 1 of 3 locations, from a policy applied to the mail-store, by setting the quotas on the mail store itself and from quotas set on the mailbox directly. So to work out what quotas apply to a user you first need to query the user object in AD and look at the mDBUseDefaults property (which relates to the use store defaults check box in AD Users and Computers). If this is set to true (which is default) then you need to look at the mail-store object to see if quotas have been applied to the store. After you have the mailbox quota information you can query the server via WMI to work out the mailbox size and then using a little math you can determine the percentage of the quota that’s been used for each user.

I came up with a couple of scripts that could do this based on the email address of the user. These scripts are designed to run with the users email address as a commandline parameter it does a lookup of Active directory based on the email address. Then checks the mDBUseDefaults property. If this is set to true it opens the mail-store object this mailbox is located on using the homemdb property and reads the quota information of the mail-store. If the mDBUseDefaults is set to false the quota information is read from the user object. The script then uses WMI to workout the mailbox size this is where the two scripts differ. The first one use’s a select statement with a Where clause and the second use the 5 key fields for the exchange_mailbox WMI class to do a direct connection via WMI. I thought the second method may have been quicker but it still a little slower then I’d like. The information is then echo'd out to the command-line and a little math I used to work out the percentage of the Quota used. These scripts are okay for one user but if your trying to do multiple users (like all the users on a server) this method is pretty slow. I started looking into ways to make this faster and one method that seemed to work although it has taken me most of the week to get it going is to use ADO data shaping to combine the data from the multiple datasources into one ADO recordset. I’m still working on this example but I should have something that’s post worthy by the next week. I’ve posted both the script I’ve talked about here as well as the slow server example.