I found this PowerShell Script that searches for Exchange Servers in the Domain.
Function Get-ExchangeServerInSite {
$ADSite = [System.DirectoryServices.ActiveDirectory.ActiveDirectorySite]
$siteDN = $ADSite::GetComputerSite().GetDirectoryEntry().distinguishedName
$configNC=([ADSI]"LDAP://RootDse").configurationNamingContext
$search = new-object DirectoryServices.DirectorySearcher([ADSI]"LDAP://$configNC")
$objectClass = "objectClass=msExchExchangeServer"
$site = "msExchServerSite=$siteDN"
$search.Filter = "(&($objectClass)($site))"
$search.PageSize=1000
[void] $search.PropertiesToLoad.Add("name")
[void] $search.PropertiesToLoad.Add("msexchcurrentserverroles")
[void] $search.PropertiesToLoad.Add("networkaddress")
$search.FindAll() | %{
New-Object PSObject -Property @{
Name = $_.Properties.name[0]
FQDN = $_.Properties.networkaddress |
%{if ($_ -match "ncacn_ip_tcp") {$_.split(":")[1]}}
Roles = $_.Properties.msexchcurrentserverroles[0]
}
}
}
$role = @{
2 = "MB"
4 = "CAS"
16 = "UM"
32 = "HT"
64 = "ET"
}
foreach ($server in Get-ExchangeServerinSite) {
$roles = ($role.keys | ?{$_ -band $server.roles} | %{$role.Get_Item($_)}) -join ", "
$server | select Name, @{n="Roles";e={$roles}},FQDN
}
Because I need the same task in C# code without using PowerShell. I tried using the .Net classes the same way and even debuged both scripts and the info is the same.
Now my problem. The PowerShell script correctly displays the server and the C# code returns an empty collection.
Here is the C#
string siteDN = ActiveDirectorySite.GetComputerSite().GetDirectoryEntry().Properties["distinguishedName"].Value.ToString();
DirectoryEntry RootDSE = new DirectoryEntry( @"LDAP://RootDSE" );
string baseStr = @"LDAP://" + RootDSE.Properties["configurationNamingContext"].Value ;
DirectorySearcher searcher = new DirectorySearcher(baseStr );
string classObj = "objectClass=msExchExchangeServer";
string site = "msExchServerSite="+siteDN;
searcher.Filter = string.Format("(&({0})({1}))",classObj,site);
searcher.PropertiesToLoad.Add( "name" );
searcher.PageSize = 1000;
searcher.ServerTimeLimit = new TimeSpan(0,1,0);
searcher.CacheResults = false;
SearchResultCollection coll = searcher.FindAll();
The only difference I could find was the [ADSI]
tag in the PowerShell code but I couldn't find out what the C# part is from that.
DirectorySearcher
- your C# code adds only one of those. – marc_s Sep 21 '12 at 12:52ServerTimeLimit
- maybe that just kicks in and then no results are returned... – marc_s Sep 21 '12 at 17:55