リモート デスクトップ サービスの役割がインストールされているかどうかを検出する

Win32_ServerFeature WMI クラスを使用して、リモート デスクトップ サービス サーバーの役割がインストールされているかどうかを検出できます。

次の C# の例は、リモート デスクトップ サービス サーバーの役割がインストールされ、実行されている場合は True を返し、それ以外の場合は false を 返すメソッドを示しています。 Win32_ServerFeature WMI クラスは Windows Server 2008 以降でのみ使用できるため、このコードは以前のバージョンの Windows と互換性がありません。

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;
}