Wednesday 10 September 2008

Exchange 2003, WMI, AD and Powershell - Part 5 (Querying AD for Exchange 2003 Information)

In previous posts in this series we have looked in particular at some of the Exchange 2003 WMI classes. So far this has required manual specification of which Exchange server you want to retrieve info from; wouldn't it be nice if you could use Powershell to find all the Exchange 2003 servers in your environment then run the WMI query against the results? Fortunately for us Exchange 2003 stores a lot of configuration information in Active Directory so we can query AD to retrieve what we need. There is a great article here which details how you can do this. We do the following:

Create a new directory object using .Net for the current AD domain.

$root= New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE")

Use ADSI to get the configuration partition of AD.

$cfgNC = [adsi]("LDAP://" + $root.Get("configurationNamingContext"))

Create a directory search object

$search = New-Object System.DirectoryServices.DirectorySearcher($cfgNC)

Filter on the Exchange Server object class - the below image should help illustrate what we are doing here. (other classes you can search on can be found here)

$search.filter = '(objectclass=msExchExchangeServer)'






Use the FindAll method to execute the search.

$ExchServer = $search.FindAll()

Finally, return the names of all the results.

$ExchServer | foreach {$_.properties.name}

Which in the example from the screenshot would produce a result:

EXCH

You can now combine this with any of the previous WMI scripts to run them against all the Exchange servers in your environment, e.g. for Top 10 largest mailboxes on each server:

$root= New-Object System.DirectoryServices.DirectoryEntry("LDAP://RootDSE")
$cfgNC = [adsi]("LDAP://" + $root.Get("configurationNamingContext"))
$search = New-Object System.DirectoryServices.DirectorySearcher($cfgNC)
$search.filter = '(objectclass=msExchExchangeServer)'
$ExchServer = $search.FindAll()

foreach ($server in $ExchServer)
{
$ExchangeServers = $ExchangeServers + $ExchServer | foreach {$_.properties.name}
}
foreach ($computer in $ExchangeServers) {
Get-Wmiobject -namespace root\MicrosoftExchangeV2 -class Exchange_Mailbox -computer $computer | sort-object Size -Descending | select-object -First 10 MailboxDisplayName,Servername,StorageGroupName,StoreName,Size}

No comments: