Using PowerShell to Retrieve DCs within a Specific Domain

The following example will use a remote PowerShell session to query a list of domain controllers under a domain name, and return the first result.

Note: This does not verify that the domain controller is online and responding to queries!

/// <summary>
/// Returns a domain controller from the specified domain
/// </summary>
/// <param name="domain">The domain to search under: example.domain.org</param>
/// <returns></returns>
public string GetSystemDomainController(string domain)  
{
 string domainController = string.Empty;
 try
 {
  WSManConnectionInfo connectionInfo = new WSManConnectionInfo(
     new Uri(exchangeRemoteServer),
     "http://schemas.microsoft.com/powershell/Microsoft.Exchange", // This shouldn't change
     PSCredential.Empty
     );
  // Skip Certificate Verification
  connectionInfo.SkipCACheck = true;
  connectionInfo.SkipCNCheck = true;
  connectionInfo.SkipRevocationCheck = true;
  connectionInfo.AuthenticationMechanism = AuthenticationMechanism.NegotiateWithImplicitCredential;
  using (Runspace runspace = RunspaceFactory.CreateRunspace(connectionInfo))
  {
   using (PowerShell powershell = PowerShell.Create())
   {
    StringBuilder psScript = new StringBuilder();
    psScript.AppendLine("Set-ADServerSettings -ViewEntireForest $true");
    psScript.AppendLine("function GetDomainController() {{");
    psScript.AppendLine("$myDomain = [System.DirectoryServices.ActiveDirectory.Domain]::GetCurrentDomain()");
    psScript.AppendLine("$subDomain = $myDomain.Forest.Domains | Where {{$_.Name -like \"{0}\" }}");
    psScript.AppendLine("$dcs = $subDomain | % {{ $_.DomainControllers }} | Select-Object name");
    psScript.AppendLine("$dcArr = foreach ($dc in $dcs) {{");
    psScript.AppendLine("$retObj = new-object psobject");
    psScript.AppendLine("$retObj | add-member noteproperty -name \"Name\" -value $dc.Name");
    psScript.AppendLine("$retObj.Name");
    psScript.AppendLine("}}");
    psScript.AppendLine("return $dcArr");
    psScript.AppendLine("}}");
    psScript.AppendLine("GetDomainController | Select-Object -First 1");

    powershell.AddScript(string.Format(psScript.ToString(), domain));

    runspace.Open();
    powershell.Runspace = runspace;

    Collection<PSObject> results = powershell.Invoke();
    if (results != null)
    {
     if (results.Count > 0)
     {
      domainController = (string)results[0].ToString();
     }
     else
     {
      domainController = string.Empty;
     }
    }
   }
  }
 }
 catch (Exception ex)
 {
  // Log your exceptions!
 }
 return domainController;
}