检查 .NET 是否在 Windows 服务器上安装了远程桌面服务 (RDS) / 远程桌面会话主机 (RDSH)

Check with .NET if Remote Desktop Services (RDS) / Remote Desktop Session Host (RDSH) is installed on a Windows Server

我需要使用 .NET 检测 windows 2008 - 2019 年是否安装了远程桌面会话主机,作为我们产品先决条件检查程序的一部分。在RDS Server上无法以执行模式安装某些部分,因此我必须告诉用户,他必须更改为安装模式...

从Windows Server 2008开始,您可以使用以下类型的代码检查是否安装了RDS角色:

static void Main(string[] args)
{
    // 14 is the identifier of the Remote Desktop Services role.
    HasServerFeatureById(14);
}

static bool HasServerFeatureById(UInt32 roleId)
{
    try
    {
        ManagementClass serviceClass = new ManagementClass("Win32_ServerFeature");
        foreach (ManagementObject feature in serviceClass.GetInstances())
        {
            if ((UInt32)feature["ID"] == roleId)
            {
                return true;
            }
        }

        return false;
    }
    catch (ManagementException)
    {
        // The most likely cause of this is that this is being called from an 
        // operating system that is not a server operating system.
    }

    return false;
}

参考:Detecting Whether the Remote Desktop Services Role Is Installed