Search code examples
c#rolesservermanager

How to determine if the "Active Directory Domain Services" role has been installed on a server


I am trying to figure out if the Active Directory Domain Services are installed a windows server.

I know they show up in the Server Manager, but can I programmatically get if the role is installed on a server using C# code


Solution

  • If you know the name of the server you want to test and can run the program with domain admin privileges remotely, you can use WMI:

    internal static bool IsDomainController(string ServerName)
    {
        StringBuilder Results = new StringBuilder();
    
        try
        {
            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("\\\\" + ServerName + "\\root\\CIMV2",
                "SELECT * FROM Win32_ServerFeature WHERE ID = 10");
    
            foreach (ManagementObject queryObj in searcher.Get())
            {
                Results.AppendLine(queryObj.GetPropertyValue("ID").ToString());
            }
        }
        catch (ManagementException)
        {
            //handle exception
        }
    
        if (Results.Length > 0)
            return true;
        else
            return false;
    }
    

    If you're running that locally on the server, the WMI path changes to:

            ManagementObjectSearcher searcher =
                new ManagementObjectSearcher("root\\CIMV2",
                "SELECT * FROM Win32_ServerFeature WHERE ID = 10");
    

    See the MSDN reference on Win32_ServerFeature for a full list of roles and their ID numbers.