我发现了这个在域中搜索 Exchange 服务器的 PowerShell 脚本。
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
}
因为我需要在不使用 PowerShell 的情况下在 C# 代码中执行相同的任务。我尝试以相同的方式使用 .Net 类,甚至调试了两个脚本并且信息是相同的。
现在我的问题。PowerShell 脚本正确显示服务器并且 C# 代码返回一个空集合。
这里是 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();
我能找到的唯一区别是[ADSI]
PowerShell 代码中的标签,但我无法从中找出 C# 部分是什么。