我发现这个PowerShell脚本在域中搜索Exchange服务器。
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
}
因为我在C#代码中需要相同的任务而不使用PowerShell。我尝试以相同的方式使用.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();
我能找到的唯一区别是PowerShell代码中的[ADSI]
标记,但我无法找到C#部分的内容。