Home:ALL Converter>Problems with accessing AD Information (PowerShell Script works, C# code dont)

Problems with accessing AD Information (PowerShell Script works, C# code dont)

Ask Time:2012-09-21T20:20:07         Author:Ryo Saeba

Json Formatter

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
    $search = new-object DirectoryServices.DirectorySearcher([ADSI]"LDAP://$configNC")
    $objectClass = "objectClass=msExchExchangeServer"
    $site = "msExchServerSite=$siteDN"
    $search.Filter = "(&($objectClass)($site))"
    [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.

Author:Ryo Saeba,eproduced under the CC 4.0 BY-SA copyright license with a link to the original source and this disclaimer.
Link to original article:https://stackoverflow.com/questions/12530507/problems-with-accessing-ad-information-powershell-script-works-c-sharp-code-do