偵測是否已安裝遠端桌面服務角色
您可以使用 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;
}